From 428877fbf69d95f7c018a8e1ad92b31b4923273d Mon Sep 17 00:00:00 2001 From: TJ Date: Sun, 22 Nov 2026 20:14:28 +0100 Subject: [PATCH] idk --- .gitignore | 6 + README.md | 58 + api/build.gradle.kts | 5 + .../ticxo/modelengine/api/ModelEngineAPI.java | 404 +++++ .../com/ticxo/modelengine/api/ServerInfo.java | 78 + .../animation/AnimationHandlerRegistry.java | 14 + .../animation/AnimationPropertyRegistry.java | 14 + .../api/animation/BlueprintAnimation.java | 186 +++ .../modelengine/api/animation/ModelState.java | 56 + .../modelengine/api/animation/Timeline.java | 76 + .../animation/handler/AnimationHandler.java | 249 ++++ .../animation/handler/IPriorityHandler.java | 44 + .../handler/IStateMachineHandler.java | 52 + .../interpolator/KeyframeInterpolator.java | 101 ++ .../interpolator/PrePostInterpolator.java | 93 ++ .../interpolator/ScriptInterpolator.java | 47 + .../api/animation/keyframe/KeyframeType.java | 177 +++ .../keyframe/KeyframeTypeRegistry.java | 19 + .../api/animation/keyframe/KeyframeTypes.java | 464 ++++++ .../animation/keyframe/data/DoubleData.java | 16 + .../keyframe/data/IKeyframeData.java | 9 + .../keyframe/data/KeyframeReaderRegistry.java | 52 + .../keyframe/type/AbstractKeyframe.java | 105 ++ .../animation/keyframe/type/IVectorType.java | 23 + .../keyframe/type/ScriptKeyframe.java | 24 + .../keyframe/type/VectorKeyframe.java | 104 ++ .../property/IAnimationProperty.java | 150 ++ .../animation/property/SimpleProperty.java | 574 ++++++++ .../animation/property/SubTickProperty.java | 319 ++++ .../api/animation/rootmotion/RootMotion.java | 10 + .../animation/rootmotion/RootMotionDelta.java | 6 + .../rootmotion/RootMotionHandler.java | 86 ++ .../api/animation/script/ScriptReader.java | 7 + .../script/ScriptReaderRegistry.java | 6 + .../api/command/AbstractCommand.java | 96 ++ .../modelengine/api/entity/BaseEntity.java | 118 ++ .../modelengine/api/entity/BukkitEntity.java | 363 +++++ .../modelengine/api/entity/BukkitPlayer.java | 71 + .../modelengine/api/entity/CullType.java | 17 + .../ticxo/modelengine/api/entity/Dummy.java | 339 +++++ .../modelengine/api/entity/DynamicBox.java | 24 + .../api/entity/EntityDataTrackers.java | 177 +++ .../ticxo/modelengine/api/entity/Hitbox.java | 106 ++ .../api/entity/cull/BasicCulling.java | 141 ++ .../api/entity/cull/ModelCuller.java | 31 + .../api/entity/data/AbstractEntityData.java | 274 ++++ .../api/entity/data/BukkitEntityData.java | 547 +++++++ .../api/entity/data/DummyEntityData.java | 186 +++ .../api/entity/data/IEntityData.java | 176 +++ .../api/entity/data/TrackingMap.java | 173 +++ .../modelengine/api/error/ErrorCollector.java | 43 + .../api/error/ErrorIncompatibleBone.java | 26 + .../error/ErrorMissingBoneBehaviorData.java | 26 + .../api/error/ErrorNoFaceCube.java | 22 + .../api/error/ErrorUnknownBoneBehavior.java | 18 + .../api/error/ErrorUnknownFormat.java | 8 + .../error/ErrorWrongBoneBehaviorDataType.java | 32 + .../ticxo/modelengine/api/error/IError.java | 50 + .../modelengine/api/error/WarnBadAngle.java | 25 + .../api/error/WarnBadEyeHeight.java | 8 + .../api/error/WarnBadNamespace.java | 15 + .../modelengine/api/error/WarnBadTexture.java | 23 + .../api/error/WarnBadTranslation.java | 37 + .../api/error/WarnBoneTooLarge.java | 33 + .../modelengine/api/error/WarnBoxUV.java | 8 + .../api/error/WarnDuplicateTexture.java | 23 + .../error/WarnIncompatibleBoneBehavior.java | 22 + .../api/error/WarnMultipleAngle.java | 22 + .../modelengine/api/error/WarnNoHitbox.java | 8 + .../api/error/WarningDuplicateBoneName.java | 23 + .../modelengine/api/events/AbstractEvent.java | 10 + .../modelengine/api/events/AddModelEvent.java | 54 + .../api/events/AnimationEndEvent.java | 35 + .../api/events/AnimationPlayEvent.java | 45 + .../api/events/BaseEntityInteractEvent.java | 138 ++ .../api/events/BoneTransformReadEvent.java | 54 + .../api/events/ModelDismountEvent.java | 58 + .../api/events/ModelMountEvent.java | 58 + .../api/events/ModelRegistrationEvent.java | 28 + .../api/events/ModelSetupEvent.java | 35 + .../events/RegisterBehaviorParserEvent.java | 39 + .../api/events/RegisterParserEvent.java | 39 + .../api/events/RemoveModelEvent.java | 45 + .../api/generator/BaseItemEnum.java | 89 ++ .../api/generator/ModelGenerator.java | 29 + .../generator/assets/BlueprintTexture.java | 134 ++ .../api/generator/assets/ItemModel.java | 113 ++ .../api/generator/assets/ItemModelData.java | 139 ++ .../api/generator/assets/JavaDisplay.java | 61 + .../api/generator/assets/JavaItemModel.java | 284 ++++ .../api/generator/assets/ModelAssets.java | 29 + .../api/generator/assets/TintSource.java | 73 + .../generator/blueprint/BlueprintBone.java | 207 +++ .../generator/blueprint/ModelBlueprint.java | 207 +++ .../api/generator/parser/ModelParser.java | 13 + .../blockbench/BlockbenchBehaviorParser.java | 11 + .../blockbench/BlockbenchDeserializer.java | 24 + .../parser/blockbench/BlockbenchModel.java | 591 ++++++++ .../parser/blockbench/LegacyDeserializer.java | 168 +++ .../parser/blockbench/v5_0_Deserializer.java | 248 ++++ .../api/generator/skin/LimbData.java | 33 + .../generator/skin/SkinGeneratorService.java | 11 + .../api/generator/skin/SkinSplitter.java | 19 + .../api/interaction/DynamicHitbox.java | 68 + .../api/interaction/InteractionTracker.java | 196 +++ .../api/lod/AnimationLODHandler.java | 220 +++ .../api/lod/BoneSnapshotHandler.java | 52 + .../modelengine/api/menu/AbstractScreen.java | 121 ++ .../modelengine/api/menu/ScreenManager.java | 39 + .../ticxo/modelengine/api/menu/Widget.java | 15 + .../modelengine/api/model/ActiveModel.java | 213 +++ .../modelengine/api/model/ModelRegistry.java | 25 + .../modelengine/api/model/ModelUpdaters.java | 283 ++++ .../modelengine/api/model/ModeledEntity.java | 132 ++ .../modelengine/api/model/PivotOverride.java | 64 + .../api/model/PivotOverrideRegistry.java | 50 + .../api/model/bone/BoneBehaviorTypes.java | 27 + .../modelengine/api/model/bone/BoneItems.java | 170 +++ .../api/model/bone/ManualAnimator.java | 7 + .../modelengine/api/model/bone/ModelBone.java | 226 +++ .../api/model/bone/SimpleManualAnimator.java | 49 + .../bone/behavior/AbstractBoneBehavior.java | 30 + .../api/model/bone/behavior/BoneBehavior.java | 117 ++ .../model/bone/behavior/BoneBehaviorData.java | 41 + .../bone/behavior/BoneBehaviorRegistry.java | 37 + .../model/bone/behavior/BoneBehaviorType.java | 300 ++++ .../bone/behavior/GlobalBehaviorData.java | 4 + .../model/bone/behavior/ProceduralType.java | 6 + .../bone/manager/AbstractBehaviorManager.java | 32 + .../model/bone/manager/BehaviorManager.java | 45 + .../api/model/bone/manager/LeashManager.java | 33 + .../api/model/bone/manager/MountData.java | 9 + .../api/model/bone/manager/MountManager.java | 101 ++ .../model/bone/render/BehaviorRenderer.java | 31 + .../bone/render/BehaviorRendererParser.java | 7 + .../model/bone/render/DefaultRenderType.java | 16 + .../api/model/bone/render/IRenderType.java | 9 + .../render/renderer/HeldItemRenderer.java | 65 + .../bone/render/renderer/LeashRenderer.java | 27 + .../bone/render/renderer/MountRenderer.java | 29 + .../bone/render/renderer/NameTagRenderer.java | 74 + .../bone/render/renderer/RenderQueues.java | 23 + .../bone/render/renderer/SegmentRenderer.java | 33 + .../render/renderer/SubHitboxRenderer.java | 38 + .../api/model/bone/type/Ghost.java | 7 + .../modelengine/api/model/bone/type/Head.java | 7 + .../api/model/bone/type/HeldItem.java | 140 ++ .../api/model/bone/type/Leash.java | 23 + .../api/model/bone/type/Mount.java | 28 + .../api/model/bone/type/NameTag.java | 71 + .../api/model/bone/type/PlayerLimb.java | 34 + .../api/model/bone/type/Segment.java | 45 + .../api/model/bone/type/SubHitbox.java | 42 + .../api/model/bone/type/UserLimb.java | 19 + .../api/model/limb/UserLimbCache.java | 197 +++ .../api/model/limb/UserLimbRegistry.java | 224 +++ .../api/model/operation/ModelOperation.java | 563 +++++++ .../api/model/operation/OperationResult.java | 11 + .../api/model/operation/OperationType.java | 137 ++ .../api/model/render/DisplayBone.java | 116 ++ .../api/model/render/DisplayFire.java | 26 + .../api/model/render/DisplayRenderer.java | 111 ++ .../api/model/render/ModelRenderer.java | 25 + .../api/model/render/ModelRendererParser.java | 7 + .../mount/MountControllerTypeRegistry.java | 7 + .../api/mount/MountPairManager.java | 95 ++ .../api/mount/controller/MountController.java | 163 +++ .../controller/MountControllerSupplier.java | 9 + .../mount/controller/MountControllerType.java | 18 + .../controller/MountControllerTypes.java | 11 + .../impl/AbstractMountController.java | 76 + .../impl/FlyingMountController.java | 56 + .../impl/WalkingMountController.java | 46 + .../ticxo/modelengine/api/nms/NMSHandler.java | 76 + .../modelengine/api/nms/RenderParsers.java | 44 + .../api/nms/entity/AttributeAccessor.java | 5 + .../api/nms/entity/EntityHandler.java | 371 +++++ .../api/nms/entity/EntityState.java | 19 + .../api/nms/entity/HitboxEntity.java | 30 + .../wrapper/BodyRotationController.java | 89 ++ .../nms/entity/wrapper/LookController.java | 16 + .../nms/entity/wrapper/MoveController.java | 42 + .../nms/entity/wrapper/MovementOverride.java | 9 + .../api/nms/entity/wrapper/TrackedEntity.java | 62 + .../impl/DefaultBodyRotationController.java | 240 +++ .../api/nms/impl/DummyTrackedEntity.java | 148 ++ .../nms/impl/EmptyBodyRotationController.java | 122 ++ .../api/nms/impl/EmptyLookController.java | 25 + .../api/nms/impl/EmptyMoveController.java | 64 + .../api/nms/impl/TempTrackedEntity.java | 138 ++ .../api/nms/network/CancelType.java | 7 + .../api/nms/network/ClientDesyncMonitor.java | 158 ++ .../api/nms/network/ModPlayerTracker.java | 26 + .../api/nms/network/NetworkHandler.java | 25 + .../api/nms/network/PipelineWrapper.java | 120 ++ .../api/nms/network/ProtectedPacket.java | 4 + .../nms/network/ProtectedPacketUnpacker.java | 15 + .../modelengine/api/nms/ui/AnvilHandler.java | 64 + .../api/utils/CompatibilityManager.java | 66 + .../api/utils/MemoizeSupplier.java | 26 + .../modelengine/api/utils/MiscUtils.java | 95 ++ .../modelengine/api/utils/MojangAPI.java | 202 +++ .../modelengine/api/utils/OffsetMode.java | 15 + .../ticxo/modelengine/api/utils/Profiler.java | 54 + .../api/utils/RaceConditionUtil.java | 46 + .../api/utils/ReflectionUtils.java | 203 +++ .../modelengine/api/utils/RunnableGroup.java | 16 + .../ticxo/modelengine/api/utils/StepFlag.java | 17 + .../ticxo/modelengine/api/utils/TFile.java | 238 +++ .../api/utils/callback/Callback.java | 33 + .../api/utils/config/ConfigCache.java | 50 + .../api/utils/config/ConfigManager.java | 94 ++ .../api/utils/config/ConfigProperty.java | 134 ++ .../api/utils/config/DebugToggle.java | 34 + .../api/utils/config/Property.java | 71 + .../api/utils/data/CachedImmutableMap.java | 41 + .../api/utils/data/ComponentUtil.java | 49 + .../modelengine/api/utils/data/ConstSet.java | 89 ++ .../modelengine/api/utils/data/GSONUtils.java | 93 ++ .../modelengine/api/utils/data/ItemUtils.java | 134 ++ .../api/utils/data/NullableHashSet.java | 10 + .../api/utils/data/PooledCollection.java | 88 ++ .../api/utils/data/PositionCodec.java | 69 + .../api/utils/data/QueuedAtomic.java | 82 ++ .../api/utils/data/QueuedBoolean.java | 33 + .../api/utils/data/QueuedDouble.java | 32 + .../api/utils/data/QueuedFloat.java | 35 + .../modelengine/api/utils/data/QueuedInt.java | 33 + .../api/utils/data/ResourceLocation.java | 75 + .../modelengine/api/utils/data/Triple.java | 38 + .../api/utils/data/UpdateScheme.java | 135 ++ .../data/interpolator/BasicInterpolator.java | 7 + .../utils/data/interpolator/Interpolator.java | 75 + .../modelengine/api/utils/data/io/DataIO.java | 15 + .../api/utils/data/io/SavedData.java | 247 ++++ .../data/tracker/CollectionDataTracker.java | 92 ++ .../api/utils/data/tracker/DataTracker.java | 70 + .../utils/data/tracker/FloatDataTracker.java | 29 + .../utils/data/tracker/MapDataTracker.java | 108 ++ .../data/tracker/QuaternionfDataTracker.java | 32 + .../utils/data/tracker/UpdateDataTracker.java | 60 + .../data/tracker/Vector3fDataTracker.java | 32 + .../api/utils/logger/LogColor.java | 33 + .../modelengine/api/utils/logger/TLogger.java | 172 +++ .../modelengine/api/utils/math/Axis.java | 19 + .../ticxo/modelengine/api/utils/math/Box.java | 10 + .../api/utils/math/ColorHelper.java | 162 ++ .../modelengine/api/utils/math/Direction.java | 38 + .../modelengine/api/utils/math/Easing.java | 163 +++ .../api/utils/math/OrientedBoundingBox.java | 243 +++ .../api/utils/math/SafeTransform.java | 90 ++ .../modelengine/api/utils/math/TMath.java | 773 ++++++++++ .../modelengine/api/utils/math/Transform.java | 137 ++ .../api/utils/meta/IMetaHolder.java | 5 + .../api/utils/meta/MetadataRegistry.java | 36 + .../utils/promise/AbstractFoliaPromise.java | 24 + .../api/utils/promise/AbstractPromise.java | 133 ++ .../api/utils/promise/EntityPromise.java | 40 + .../api/utils/promise/GlobalPromise.java | 36 + .../api/utils/promise/LegacyPromise.java | 54 + .../api/utils/promise/Promise.java | 168 +++ .../api/utils/promise/RegionPromise.java | 41 + .../api/utils/registry/TRegistry.java | 47 + .../api/utils/registry/TUnaryRegistry.java | 23 + .../resourcepack/ResourcePackFeature.java | 7 + .../resourcepack/ResourcePackVersion.java | 61 + .../scheduling/BukkitPlatformScheduler.java | 28 + .../utils/scheduling/BukkitPlatformTask.java | 16 + .../scheduling/FoliaPlatformScheduler.java | 33 + .../utils/scheduling/FoliaPlatformTask.java | 16 + .../utils/scheduling/PlatformScheduler.java | 15 + .../api/utils/scheduling/PlatformTask.java | 5 + .../api/utils/state/StateMachine.java | 56 + .../api/utils/state/StateNode.java | 146 ++ .../utils/ticker/AbstractLoadBalancer.java | 65 + .../api/utils/ticker/AsyncTaskExecutor.java | 31 + .../api/utils/ticker/DualTicker.java | 82 ++ .../api/utils/ticker/LoadBalancer.java | 24 + .../api/utils/ticker/PseudoThread.java | 115 ++ .../modelengine/api/utils/ticker/Task.java | 64 + .../com/ticxo/modelengine/api/vfx/VFX.java | 117 ++ .../ticxo/modelengine/api/vfx/VFXUpdater.java | 94 ++ .../api/vfx/render/VFXDisplayRenderer.java | 58 + .../api/vfx/render/VFXRenderer.java | 17 + .../api/vfx/render/VFXRendererParser.java | 7 + build.gradle.kts | 117 ++ core/build.gradle.kts | 10 + .../ticxo/modelengine/core/ModelEngine.java | 428 ++++++ .../animation/handler/PriorityHandler.java | 409 ++++++ .../handler/StateMachineHandler.java | 720 +++++++++ .../script/ModelEngineScriptReader.java | 222 +++ .../modelengine/core/citizens/BugTrait.java | 37 + .../core/citizens/CitizensCommand.java | 394 +++++ .../modelengine/core/citizens/ModelTrait.java | 68 + .../modelengine/core/command/MECommand.java | 106 ++ .../core/command/ModelOptionParser.java | 210 +++ .../core/command/sub/DebugCommand.java | 77 + .../core/command/sub/DisguiseCommand.java | 93 ++ .../core/command/sub/MenuCommand.java | 42 + .../core/command/sub/PluginHealthCommand.java | 57 + .../core/command/sub/ReloadCommand.java | 94 ++ .../core/command/sub/ResyncCommand.java | 48 + .../core/command/sub/SummonCommand.java | 111 ++ .../core/command/sub/TestCommand.java | 36 + .../core/command/sub/ToggleLODCommand.java | 58 + .../core/command/sub/UndisguiseCommand.java | 76 + .../modelengine/core/data/DataUpdater.java | 67 + .../ticxo/modelengine/core/data/V3Data.java | 752 ++++++++++ .../core/generator/BaseItemManager.java | 271 ++++ .../core/generator/ModelCacheGroup.java | 9 + .../core/generator/ModelGeneratorImpl.java | 820 +++++++++++ .../core/generator/ModelIdCache.java | 86 ++ .../core/generator/PaletteImageWriter.java | 194 +++ .../core/generator/atlas/Atlas.java | 52 + .../core/generator/atlas/AtlasManager.java | 66 + .../core/generator/java/BaseItem.java | 64 + .../generator/java/BaseItemTransformer.java | 59 + .../parser/blockbench/BlockbenchParser.java | 583 ++++++++ .../json/DefaultBehaviorParser.java | 371 +++++ .../blockbench/json/MCMetaDeserializer.java | 38 + .../generator/processed/ProcessedBone.java | 200 +++ .../core/generator/skin/FaceMapper.java | 61 + .../skin/MineSkinGeneratorService.java | 94 ++ .../core/generator/skin/PlayerMapper.java | 86 ++ .../core/generator/skin/SkinSplitterImpl.java | 142 ++ .../core/generator/util/HashedVector3d.java | 33 + .../generator/util/IllegalRotationSolver.java | 120 ++ .../core/generator/util/ItemGroup.java | 104 ++ .../core/generator/util/PlaneGroup.java | 40 + .../core/generator/util/RotationSolver.java | 343 +++++ .../core/javasupport/Java21Access.java | 59 + .../core/javasupport/Java25Access.java | 55 + .../libsdisguises/DisguiseCompatibility.java | 32 + .../core/listener/ChatListener.java | 31 + .../core/listener/EntityListener.java | 119 ++ .../core/listener/InventoryListener.java | 46 + .../core/listener/PlayerListener.java | 119 ++ .../core/listener/WorldListener.java | 195 +++ .../core/menu/SelectionManager.java | 44 + .../core/menu/screen/AddModelScreen.java | 76 + .../core/menu/screen/EditEntityScreen.java | 372 +++++ .../core/menu/screen/EditModelScreen.java | 683 +++++++++ .../core/menu/screen/NavigationScreen.java | 139 ++ .../core/menu/screen/SpawnModelScreen.java | 76 + .../core/menu/widget/BasicItemWidget.java | 26 + .../core/menu/widget/BorderWidget.java | 34 + .../core/menu/widget/CloseWidget.java | 38 + .../core/menu/widget/CompositeWidget.java | 29 + .../core/menu/widget/PaginatorWidget.java | 119 ++ .../core/menu/widget/TabWidget.java | 65 + .../menu/widget/page/AbstractModelButton.java | 55 + .../modelengine/core/misc/Alternator.java | 133 ++ .../ticxo/modelengine/core/misc/Cardinal.java | 54 + .../core/model/ActiveModelImpl.java | 896 ++++++++++++ .../modelengine/core/model/BoneSequencer.java | 48 + .../core/model/ModeledEntityImpl.java | 624 ++++++++ .../core/model/bone/ModelBoneImpl.java | 1186 +++++++++++++++ .../bone/behavior/AbstractSegmentImpl.java | 354 +++++ .../core/model/bone/behavior/Dummy.java | 12 + .../core/model/bone/behavior/GhostImpl.java | 25 + .../model/bone/behavior/HeadForcedImpl.java | 71 + .../core/model/bone/behavior/HeadImpl.java | 88 ++ .../model/bone/behavior/HeldItemImpl.java | 114 ++ .../core/model/bone/behavior/LeashImpl.java | 92 ++ .../core/model/bone/behavior/MountImpl.java | 142 ++ .../core/model/bone/behavior/NameTagImpl.java | 215 +++ .../model/bone/behavior/PlayerLimbImpl.java | 77 + .../core/model/bone/behavior/SegmentImpl.java | 51 + .../model/bone/behavior/SubHitboxImpl.java | 226 +++ .../core/model/bone/behavior/TailImpl.java | 11 + .../model/bone/behavior/UserLimbImpl.java | 156 ++ .../model/bone/manager/LeashManagerImpl.java | 86 ++ .../model/bone/manager/MountDataImpl.java | 21 + .../model/bone/manager/MountManagerImpl.java | 497 +++++++ .../bone/render/AbstractBehaviorRenderer.java | 32 + .../bone/render/HeldItemRendererImpl.java | 239 +++ .../model/bone/render/LeashRendererImpl.java | 193 +++ .../model/bone/render/MountRendererImpl.java | 217 +++ .../bone/render/NameTagRendererImpl.java | 277 ++++ .../bone/render/SegmentRendererImpl.java | 361 +++++ .../bone/render/SubHitboxRendererImpl.java | 190 +++ .../core/model/render/DisplayBoneImpl.java | 242 +++ .../core/model/render/DisplayFireImpl.java | 60 + .../model/render/DisplayRendererImpl.java | 796 ++++++++++ .../ticxo/modelengine/core/vfx/VFXImpl.java | 289 ++++ .../vfx/render/VFXDisplayRendererImpl.java | 193 +++ core/src/main/resources/config.yml | 86 ++ .../resources/internal/alex_mapped.bbmodel | 1300 +++++++++++++++++ .../resources/internal/internal_fire.bbmodel | 258 ++++ .../resources/internal/player_model.bbmodel | 1262 ++++++++++++++++ .../resources/internal/steve_mapped.bbmodel | 1300 +++++++++++++++++ .../assets/minecraft/shaders/core/entity.fsh | 147 ++ .../assets/minecraft/shaders/core/entity.vsh | 258 ++++ .../core/rendertype_entity_translucent.fsh | 47 + .../core/rendertype_entity_translucent.json | 34 + .../core/rendertype_entity_translucent.vsh | 205 +++ .../shaders/include/player_shader.glsl | 11 + .../assets/modelengine/items/player_head.json | 119 ++ .../models/custom/entities/player/head.json | 1 + .../custom/entities/player/left_arm.json | 1 + .../custom/entities/player/left_leg.json | 1 + .../custom/entities/player/right_arm.json | 1 + .../custom/entities/player/right_leg.json | 1 + .../custom/entities/player/slim_left.json | 1 + .../custom/entities/player/slim_right.json | 1 + .../models/custom/entities/player/torso.json | 1 + .../resources/pack/colorable/filled_map.json | 7 + .../pack/colorable/leather_boots.json | 7 + .../pack/colorable/leather_chestplate.json | 7 + .../pack/colorable/leather_horse_armor.json | 7 + .../pack/colorable/leather_leggings.json | 7 + .../pack/colorable/lingering_potion.json | 7 + .../main/resources/pack/colorable/potion.json | 7 + .../pack/colorable/splash_potion.json | 7 + .../pack/colorable/tipped_arrow.json | 7 + .../minecraft/models/item/player_head.json | 13 + .../assets/minecraft/shaders/core/entity.fsh | 35 + .../assets/minecraft/shaders/core/entity.vsh | 46 + .../core/rendertype_entity_translucent.fsh | 47 + .../core/rendertype_entity_translucent.json | 34 + .../core/rendertype_entity_translucent.vsh | 205 +++ .../assets/modelengine/items/player_head.json | 104 ++ .../assets/minecraft/shaders/core/entity.fsh | 73 + .../assets/minecraft/shaders/core/entity.vsh | 219 +++ .../assets/minecraft/shaders/core/entity.fsh | 68 + .../assets/minecraft/shaders/core/entity.vsh | 216 +++ .../assets/minecraft/shaders/core/entity.fsh | 102 ++ .../assets/minecraft/shaders/core/entity.vsh | 248 ++++ .../assets/minecraft/shaders/core/entity.fsh | 102 ++ .../assets/minecraft/shaders/core/entity.vsh | 250 ++++ core/src/main/resources/pack/pack.mcmeta | 82 ++ core/src/main/resources/pack/pack.png | Bin 0 -> 6586 bytes core/src/main/resources/plugin.yml | 25 + core21/build.gradle.kts | 8 + .../modelengine/core21/Java21Helper.java | 47 + .../core21/mythic/MythicUtils.java | 216 +++ .../mythic/animation/MythicScriptReader.java | 50 + .../mythic/compatibility/AuraAttachment.java | 144 ++ .../mythic/compatibility/FakeEntity.java | 68 + .../core21/mythic/compatibility/MEGModel.java | 108 ++ .../compatibility/ModelEngineSupportImpl.java | 129 ++ .../compatibility/MythicCompatibility.java | 66 + .../compatibility/MythicMountController.java | 68 + .../compatibility/ProjectileBullet.java | 160 ++ .../mythic/compatibility/ProjectileData.java | 176 +++ .../compatibility/ProjectileEntity.java | 232 +++ .../mythic/conditions/HasModelCondition.java | 51 + .../mythic/conditions/HitboxCondition.java | 30 + .../HitboxIsSubHitboxCondition.java | 31 + .../conditions/IsDrivingModelCondition.java | 31 + .../conditions/IsRidingModelCondition.java | 31 + .../conditions/ModelHasDriverCondition.java | 33 + .../ModelHasPassengerCondition.java | 155 ++ .../mechanics/bone/AnimateModelMechanic.java | 201 +++ .../mechanics/bone/BillboardMechanic.java | 99 ++ .../mechanics/bone/BrightnessMechanic.java | 99 ++ .../mechanics/bone/ChangeParentMechanic.java | 81 + .../mechanics/bone/ChangePartMechanic.java | 99 ++ .../mechanics/bone/CyclePartsMechanic.java | 112 ++ .../mechanics/bone/EnchantMechanic.java | 85 ++ .../mythic/mechanics/bone/GlowMechanic.java | 140 ++ .../mechanics/bone/ModelSkinMechanic.java | 155 ++ .../bone/PartVisibilityMechanic.java | 79 + .../mechanics/bone/SegmentMechanic.java | 236 +++ .../mythic/mechanics/bone/TintMechanic.java | 108 ++ .../mechanics/controller/JumpMechanic.java | 32 + .../mechanics/controller/MoveMechanic.java | 64 + .../mechanics/controller/NoFallMechanic.java | 32 + .../mechanics/controller/SyncYawMechanic.java | 61 + .../mechanics/disguise/DisguiseMechanic.java | 70 + .../disguise/UndisguiseMechanic.java | 64 + .../entity/BodyRotationMechanic.java | 94 ++ .../entity/ConfigureCullMechanic.java | 127 ++ .../mechanics/entity/ModelMechanic.java | 187 +++ .../mechanics/entity/PairModelMechanic.java | 60 + .../mechanics/entity/PetrifyMechanic.java | 40 + .../mechanics/hitbox/BindHitboxMechanic.java | 116 ++ .../hitbox/ConfigureHitboxMechanic.java | 55 + .../mechanics/item/LinkItemBoneMechanic.java | 70 + .../mechanics/item/SetItemModelMechanic.java | 137 ++ .../mythic/mechanics/leash/LeashMechanic.java | 62 + .../mechanics/leash/LeashSelfMechanic.java | 50 + .../mechanics/model/DefaultStateMechanic.java | 86 ++ .../mechanics/model/LockHeadMechanic.java | 50 + .../model/LockModelRotationMechanic.java | 69 + .../mechanics/model/ModifyStateMechanic.java | 116 ++ .../mechanics/model/RemapModelMechanic.java | 147 ++ .../mechanics/model/RendererInitMechanic.java | 46 + .../mechanics/model/RootMotionMechanic.java | 59 + .../mythic/mechanics/model/ScaleMechanic.java | 73 + .../mythic/mechanics/model/StateMechanic.java | 201 +++ .../mechanics/model/StateToggleMechanic.java | 160 ++ .../mechanics/model/SubModelMechanic.java | 109 ++ .../mechanics/model/SwapEntityMechanic.java | 75 + .../mounting/DismountAllMechanic.java | 67 + .../mounting/DismountModelMechanic.java | 86 ++ .../mounting/MountModelMechanic.java | 179 +++ .../mechanics/nametag/SetNametagMechanic.java | 105 ++ .../nametag/SetNametagVisibilityMechanic.java | 54 + .../mechanics/vfx/VFXBrightnessMechanic.java | 56 + .../mechanics/vfx/VFXChangeModelMechanic.java | 66 + .../mechanics/vfx/VFXEnchantMechanic.java | 51 + .../mythic/mechanics/vfx/VFXMechanic.java | 128 ++ .../vfx/VFXResetPositionMechanic.java | 45 + .../vfx/VFXResetRotationMechanic.java | 45 + .../mechanics/vfx/VFXResetScaleMechanic.java | 45 + .../mechanics/vfx/VFXSetPositionMechanic.java | 87 ++ .../mechanics/vfx/VFXSetRotationMechanic.java | 131 ++ .../mechanics/vfx/VFXSetScaleMechanic.java | 87 ++ .../vfx/VFXSetVisibilityMechanic.java | 51 + .../mythic/mechanics/vfx/VFXTintMechanic.java | 129 ++ .../CasterModelRotationPlaceholder.java | 31 + .../mythic/targeters/ModelDriverTargeter.java | 37 + .../mythic/targeters/ModelPartTargeter.java | 102 ++ .../targeters/ModelPassengersTargeter.java | 72 + .../targeters/MountedModelTargeter.java | 34 + .../utils/ModelEngineComponentRegistry.java | 233 +++ .../core21/mythic/utils/MythicCondition.java | 21 + .../core21/mythic/utils/MythicMechanic.java | 21 + .../core21/mythic/utils/MythicTargeter.java | 21 + core25/build.gradle.kts | 4 + .../modelengine/core25/Java25Helper.java | 17 + gradle.properties | 6 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 49154 bytes gradle/wrapper/gradle-wrapper.properties | 9 + gradlew | 248 ++++ gradlew.bat | 112 ++ libs/mineskin-java-client-3.2.1-SNAPSHOT.jar | Bin 0 -> 87826 bytes .../ticxo/modelengine/v1_19_R3/NMSFields.java | 57 + .../v1_19_R3/NMSHandler_v1_19_R3.java | 182 +++ .../modelengine/v1_19_R3/NMSMethods.java | 45 + .../v1_19_R3/entity/EntityHandlerImpl.java | 687 +++++++++ .../v1_19_R3/entity/EntityMetadataID.java | 36 + .../v1_19_R3/entity/EntityUtils.java | 27 + .../v1_19_R3/entity/OcclusionClipContext.java | 115 ++ .../v1_19_R3/entity/TrackedEntityImpl.java | 286 ++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 143 ++ .../entity/controller/MoveControlWrapper.java | 247 ++++ .../entity/hitbox/HitboxEntityImpl.java | 284 ++++ .../v1_19_R3/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 452 ++++++ .../v1_19_R3/network/NetworkHandlerImpl.java | 140 ++ .../PatchedServerGamePacketListener.java | 399 +++++ .../ServerboundInteractPacketWrapper.java | 63 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_19_R3/network/utils/Bundler.java | 65 + .../v1_19_R3/network/utils/NetworkUtils.java | 271 ++++ .../network/utils/PacketInterceptor.java | 83 ++ .../v1_19_R3/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 202 +++ .../v1_19_R3/parser/behavior/LeashParser.java | 176 +++ .../v1_19_R3/parser/behavior/MountParser.java | 244 ++++ .../parser/behavior/NameTagParser.java | 196 +++ .../parser/behavior/SegmentParser.java | 224 +++ .../parser/behavior/SubHitboxParser.java | 163 +++ .../v1_19_R3/parser/model/DisplayParser.java | 735 ++++++++++ .../v1_19_R3/parser/vfx/VFXDisplayParser.java | 142 ++ .../ticxo/modelengine/v1_20_R1/NMSFields.java | 57 + .../v1_20_R1/NMSHandler_v1_20_R1.java | 182 +++ .../modelengine/v1_20_R1/NMSMethods.java | 45 + .../v1_20_R1/entity/EntityHandlerImpl.java | 687 +++++++++ .../v1_20_R1/entity/EntityMetadataID.java | 36 + .../v1_20_R1/entity/EntityUtils.java | 27 + .../v1_20_R1/entity/OcclusionClipContext.java | 115 ++ .../v1_20_R1/entity/TrackedEntityImpl.java | 286 ++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 143 ++ .../entity/controller/MoveControlWrapper.java | 247 ++++ .../entity/hitbox/HitboxEntityImpl.java | 269 ++++ .../v1_20_R1/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 452 ++++++ .../v1_20_R1/network/NetworkHandlerImpl.java | 140 ++ .../PatchedServerGamePacketListener.java | 408 ++++++ .../ServerboundInteractPacketWrapper.java | 63 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_20_R1/network/utils/Bundler.java | 65 + .../v1_20_R1/network/utils/NetworkUtils.java | 271 ++++ .../network/utils/PacketInterceptor.java | 83 ++ .../v1_20_R1/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 198 +++ .../v1_20_R1/parser/behavior/LeashParser.java | 176 +++ .../v1_20_R1/parser/behavior/MountParser.java | 244 ++++ .../parser/behavior/NameTagParser.java | 196 +++ .../parser/behavior/SegmentParser.java | 220 +++ .../parser/behavior/SubHitboxParser.java | 163 +++ .../v1_20_R1/parser/model/DisplayParser.java | 732 ++++++++++ .../v1_20_R1/parser/vfx/VFXDisplayParser.java | 138 ++ .../ticxo/modelengine/v1_20_R2/NMSFields.java | 58 + .../v1_20_R2/NMSHandler_v1_20_R2.java | 182 +++ .../modelengine/v1_20_R2/NMSMethods.java | 48 + .../v1_20_R2/entity/EntityHandlerImpl.java | 714 +++++++++ .../v1_20_R2/entity/EntityMetadataID.java | 36 + .../v1_20_R2/entity/EntityUtils.java | 27 + .../v1_20_R2/entity/OcclusionClipContext.java | 115 ++ .../v1_20_R2/entity/TrackedEntityImpl.java | 286 ++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 143 ++ .../entity/controller/MoveControlWrapper.java | 247 ++++ .../entity/hitbox/HitboxEntityImpl.java | 269 ++++ .../v1_20_R2/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 439 ++++++ .../v1_20_R2/network/NetworkHandlerImpl.java | 140 ++ .../PatchedServerGamePacketListener.java | 408 ++++++ .../ServerboundInteractPacketWrapper.java | 63 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_20_R2/network/utils/Bundler.java | 65 + .../v1_20_R2/network/utils/NetworkUtils.java | 271 ++++ .../network/utils/PacketInterceptor.java | 83 ++ .../v1_20_R2/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 198 +++ .../v1_20_R2/parser/behavior/LeashParser.java | 176 +++ .../v1_20_R2/parser/behavior/MountParser.java | 244 ++++ .../parser/behavior/NameTagParser.java | 196 +++ .../parser/behavior/SegmentParser.java | 220 +++ .../parser/behavior/SubHitboxParser.java | 163 +++ .../v1_20_R2/parser/model/DisplayParser.java | 732 ++++++++++ .../v1_20_R2/parser/vfx/VFXDisplayParser.java | 138 ++ .../ticxo/modelengine/v1_20_R3/NMSFields.java | 59 + .../v1_20_R3/NMSHandler_v1_20_R3.java | 190 +++ .../modelengine/v1_20_R3/NMSMethods.java | 48 + .../v1_20_R3/entity/EntityHandlerImpl.java | 714 +++++++++ .../v1_20_R3/entity/EntityMetadataID.java | 36 + .../v1_20_R3/entity/EntityUtils.java | 27 + .../v1_20_R3/entity/OcclusionClipContext.java | 116 ++ .../v1_20_R3/entity/TrackedEntityImpl.java | 286 ++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 143 ++ .../entity/controller/MoveControlWrapper.java | 247 ++++ .../entity/hitbox/HitboxEntityImpl.java | 294 ++++ .../v1_20_R3/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 439 ++++++ .../v1_20_R3/network/NetworkHandlerImpl.java | 140 ++ .../PatchedServerGamePacketListener.java | 408 ++++++ .../ServerboundInteractPacketWrapper.java | 63 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_20_R3/network/utils/Bundler.java | 65 + .../v1_20_R3/network/utils/NetworkUtils.java | 271 ++++ .../network/utils/PacketInterceptor.java | 83 ++ .../v1_20_R3/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 198 +++ .../v1_20_R3/parser/behavior/LeashParser.java | 176 +++ .../v1_20_R3/parser/behavior/MountParser.java | 244 ++++ .../parser/behavior/NameTagParser.java | 195 +++ .../parser/behavior/SegmentParser.java | 220 +++ .../parser/behavior/SubHitboxParser.java | 163 +++ .../v1_20_R3/parser/model/DisplayParser.java | 732 ++++++++++ .../v1_20_R3/parser/vfx/VFXDisplayParser.java | 138 ++ .../v1_20_R3/ui/AnvilHandlerImpl.java | 111 ++ .../ticxo/modelengine/v1_20_R4/NMSFields.java | 59 + .../v1_20_R4/NMSHandler_v1_20_R4.java | 179 +++ .../modelengine/v1_20_R4/NMSMethods.java | 48 + .../v1_20_R4/entity/EntityContainer.java | 52 + .../v1_20_R4/entity/EntityHandlerImpl.java | 731 +++++++++ .../v1_20_R4/entity/EntityMetadataID.java | 36 + .../v1_20_R4/entity/EntityUtils.java | 32 + .../v1_20_R4/entity/OcclusionClipContext.java | 116 ++ .../v1_20_R4/entity/TrackedEntityImpl.java | 286 ++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 143 ++ .../entity/controller/MoveControlWrapper.java | 246 ++++ .../entity/hitbox/HitboxEntityImpl.java | 297 ++++ .../v1_20_R4/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 407 ++++++ .../v1_20_R4/network/NetworkHandlerImpl.java | 141 ++ .../PatchedServerGamePacketListener.java | 419 ++++++ .../ServerboundInteractPacketWrapper.java | 75 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_20_R4/network/utils/Bundler.java | 65 + .../v1_20_R4/network/utils/NetworkUtils.java | 336 +++++ .../network/utils/PacketInterceptor.java | 84 ++ .../v1_20_R4/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 180 +++ .../v1_20_R4/parser/behavior/LeashParser.java | 158 ++ .../v1_20_R4/parser/behavior/MountParser.java | 197 +++ .../parser/behavior/NameTagParser.java | 191 +++ .../parser/behavior/SegmentParser.java | 205 +++ .../parser/behavior/SubHitboxParser.java | 148 ++ .../v1_20_R4/parser/model/DisplayParser.java | 789 ++++++++++ .../v1_20_R4/parser/vfx/VFXDisplayParser.java | 131 ++ .../ticxo/modelengine/v1_21_R1/NMSFields.java | 59 + .../v1_21_R1/NMSHandler_v1_21_R1.java | 179 +++ .../modelengine/v1_21_R1/NMSMethods.java | 48 + .../v1_21_R1/entity/EntityContainer.java | 52 + .../v1_21_R1/entity/EntityHandlerImpl.java | 731 +++++++++ .../v1_21_R1/entity/EntityMetadataID.java | 36 + .../v1_21_R1/entity/EntityUtils.java | 30 + .../v1_21_R1/entity/OcclusionClipContext.java | 116 ++ .../v1_21_R1/entity/TrackedEntityImpl.java | 286 ++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 143 ++ .../entity/controller/MoveControlWrapper.java | 246 ++++ .../entity/hitbox/HitboxEntityImpl.java | 305 ++++ .../v1_21_R1/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 426 ++++++ .../v1_21_R1/network/NetworkHandlerImpl.java | 141 ++ .../PatchedServerGamePacketListener.java | 437 ++++++ .../ServerboundInteractPacketWrapper.java | 75 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_21_R1/network/utils/Bundler.java | 65 + .../v1_21_R1/network/utils/NetworkUtils.java | 336 +++++ .../network/utils/PacketInterceptor.java | 84 ++ .../v1_21_R1/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 180 +++ .../v1_21_R1/parser/behavior/LeashParser.java | 158 ++ .../v1_21_R1/parser/behavior/MountParser.java | 197 +++ .../parser/behavior/NameTagParser.java | 184 +++ .../parser/behavior/SegmentParser.java | 205 +++ .../parser/behavior/SubHitboxParser.java | 148 ++ .../v1_21_R1/parser/model/DisplayParser.java | 789 ++++++++++ .../v1_21_R1/parser/vfx/VFXDisplayParser.java | 124 ++ .../ticxo/modelengine/v1_21_R2/NMSFields.java | 59 + .../v1_21_R2/NMSHandler_v1_21_R2.java | 179 +++ .../modelengine/v1_21_R2/NMSMethods.java | 48 + .../v1_21_R2/entity/EntityContainer.java | 59 + .../v1_21_R2/entity/EntityHandlerImpl.java | 742 ++++++++++ .../v1_21_R2/entity/EntityMetadataID.java | 36 + .../v1_21_R2/entity/EntityUtils.java | 30 + .../v1_21_R2/entity/OcclusionClipContext.java | 116 ++ .../v1_21_R2/entity/TrackedEntityImpl.java | 286 ++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 143 ++ .../entity/controller/MoveControlWrapper.java | 263 ++++ .../entity/hitbox/HitboxEntityImpl.java | 308 ++++ .../v1_21_R2/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 457 ++++++ .../v1_21_R2/network/NetworkHandlerImpl.java | 141 ++ .../PatchedServerGamePacketListener.java | 439 ++++++ .../ServerboundInteractPacketWrapper.java | 75 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_21_R2/network/utils/Bundler.java | 65 + .../v1_21_R2/network/utils/NetworkUtils.java | 343 +++++ .../network/utils/PacketInterceptor.java | 84 ++ .../v1_21_R2/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 181 +++ .../v1_21_R2/parser/behavior/LeashParser.java | 158 ++ .../v1_21_R2/parser/behavior/MountParser.java | 197 +++ .../parser/behavior/NameTagParser.java | 184 +++ .../parser/behavior/SegmentParser.java | 205 +++ .../parser/behavior/SubHitboxParser.java | 148 ++ .../v1_21_R2/parser/model/DisplayParser.java | 789 ++++++++++ .../v1_21_R2/parser/vfx/VFXDisplayParser.java | 124 ++ .../ticxo/modelengine/v1_21_R3/NMSFields.java | 59 + .../v1_21_R3/NMSHandler_v1_21_R3.java | 231 +++ .../modelengine/v1_21_R3/NMSMethods.java | 49 + .../v1_21_R3/entity/EntityContainer.java | 59 + .../v1_21_R3/entity/EntityHandlerImpl.java | 742 ++++++++++ .../v1_21_R3/entity/EntityMetadataID.java | 36 + .../v1_21_R3/entity/EntityUtils.java | 30 + .../v1_21_R3/entity/OcclusionClipContext.java | 116 ++ .../v1_21_R3/entity/TrackedEntityImpl.java | 286 ++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 152 ++ .../entity/controller/MoveControlWrapper.java | 272 ++++ .../entity/hitbox/HitboxEntityImpl.java | 308 ++++ .../v1_21_R3/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 457 ++++++ .../v1_21_R3/network/NetworkHandlerImpl.java | 141 ++ .../PatchedServerGamePacketListener.java | 439 ++++++ .../ServerboundInteractPacketWrapper.java | 75 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_21_R3/network/utils/Bundler.java | 65 + .../v1_21_R3/network/utils/NetworkUtils.java | 343 +++++ .../network/utils/PacketInterceptor.java | 84 ++ .../v1_21_R3/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 181 +++ .../v1_21_R3/parser/behavior/LeashParser.java | 158 ++ .../v1_21_R3/parser/behavior/MountParser.java | 197 +++ .../parser/behavior/NameTagParser.java | 184 +++ .../parser/behavior/SegmentParser.java | 205 +++ .../parser/behavior/SubHitboxParser.java | 148 ++ .../v1_21_R3/parser/model/DisplayParser.java | 789 ++++++++++ .../v1_21_R3/parser/vfx/VFXDisplayParser.java | 124 ++ .../ticxo/modelengine/v1_21_R4/NMSFields.java | 59 + .../v1_21_R4/NMSHandler_v1_21_R4.java | 231 +++ .../modelengine/v1_21_R4/NMSMethods.java | 49 + .../v1_21_R4/entity/EntityContainer.java | 59 + .../v1_21_R4/entity/EntityHandlerImpl.java | 742 ++++++++++ .../v1_21_R4/entity/EntityMetadataID.java | 36 + .../v1_21_R4/entity/EntityUtils.java | 30 + .../v1_21_R4/entity/OcclusionClipContext.java | 116 ++ .../v1_21_R4/entity/TrackedEntityImpl.java | 286 ++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 152 ++ .../entity/controller/MoveControlWrapper.java | 272 ++++ .../entity/hitbox/HitboxEntityImpl.java | 271 ++++ .../v1_21_R4/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 457 ++++++ .../v1_21_R4/network/NetworkHandlerImpl.java | 141 ++ .../PatchedServerGamePacketListener.java | 439 ++++++ .../ServerboundInteractPacketWrapper.java | 75 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_21_R4/network/utils/Bundler.java | 65 + .../v1_21_R4/network/utils/NetworkUtils.java | 344 +++++ .../network/utils/PacketInterceptor.java | 84 ++ .../v1_21_R4/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 181 +++ .../v1_21_R4/parser/behavior/LeashParser.java | 158 ++ .../v1_21_R4/parser/behavior/MountParser.java | 197 +++ .../parser/behavior/NameTagParser.java | 184 +++ .../parser/behavior/SegmentParser.java | 205 +++ .../parser/behavior/SubHitboxParser.java | 148 ++ .../v1_21_R4/parser/model/DisplayParser.java | 789 ++++++++++ .../v1_21_R4/parser/vfx/VFXDisplayParser.java | 124 ++ .../ticxo/modelengine/v1_21_R5/NMSFields.java | 59 + .../v1_21_R5/NMSHandler_v1_21_R5.java | 231 +++ .../modelengine/v1_21_R5/NMSMethods.java | 49 + .../v1_21_R5/entity/EntityContainer.java | 60 + .../v1_21_R5/entity/EntityHandlerImpl.java | 755 ++++++++++ .../v1_21_R5/entity/EntityMetadataID.java | 37 + .../v1_21_R5/entity/EntityUtils.java | 33 + .../v1_21_R5/entity/OcclusionClipContext.java | 116 ++ .../v1_21_R5/entity/TrackedEntityImpl.java | 286 ++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 152 ++ .../entity/controller/MoveControlWrapper.java | 272 ++++ .../entity/hitbox/HitboxEntityImpl.java | 271 ++++ .../v1_21_R5/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 457 ++++++ .../v1_21_R5/network/NetworkHandlerImpl.java | 141 ++ .../PatchedServerGamePacketListener.java | 439 ++++++ .../ServerboundInteractPacketWrapper.java | 75 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_21_R5/network/utils/Bundler.java | 65 + .../v1_21_R5/network/utils/NetworkUtils.java | 354 +++++ .../network/utils/PacketInterceptor.java | 84 ++ .../v1_21_R5/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 186 +++ .../v1_21_R5/parser/behavior/LeashParser.java | 158 ++ .../v1_21_R5/parser/behavior/MountParser.java | 197 +++ .../parser/behavior/NameTagParser.java | 184 +++ .../parser/behavior/SegmentParser.java | 205 +++ .../parser/behavior/SubHitboxParser.java | 148 ++ .../v1_21_R5/parser/model/DisplayParser.java | 789 ++++++++++ .../v1_21_R5/parser/vfx/VFXDisplayParser.java | 124 ++ .../ticxo/modelengine/v1_21_R6/NMSFields.java | 59 + .../v1_21_R6/NMSHandler_v1_21_R6.java | 231 +++ .../modelengine/v1_21_R6/NMSMethods.java | 49 + .../v1_21_R6/entity/EntityContainer.java | 60 + .../v1_21_R6/entity/EntityHandlerImpl.java | 755 ++++++++++ .../v1_21_R6/entity/EntityMetadataID.java | 37 + .../v1_21_R6/entity/EntityUtils.java | 33 + .../v1_21_R6/entity/OcclusionClipContext.java | 116 ++ .../v1_21_R6/entity/TrackedEntityImpl.java | 286 ++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 152 ++ .../entity/controller/MoveControlWrapper.java | 272 ++++ .../entity/hitbox/HitboxEntityImpl.java | 271 ++++ .../v1_21_R6/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 457 ++++++ .../v1_21_R6/network/NetworkHandlerImpl.java | 141 ++ .../PatchedServerGamePacketListener.java | 439 ++++++ .../ServerboundInteractPacketWrapper.java | 75 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_21_R6/network/utils/Bundler.java | 65 + .../v1_21_R6/network/utils/NetworkUtils.java | 354 +++++ .../network/utils/PacketInterceptor.java | 84 ++ .../v1_21_R6/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 186 +++ .../v1_21_R6/parser/behavior/LeashParser.java | 158 ++ .../v1_21_R6/parser/behavior/MountParser.java | 197 +++ .../parser/behavior/NameTagParser.java | 184 +++ .../parser/behavior/SegmentParser.java | 205 +++ .../parser/behavior/SubHitboxParser.java | 148 ++ .../v1_21_R6/parser/model/DisplayParser.java | 789 ++++++++++ .../v1_21_R6/parser/vfx/VFXDisplayParser.java | 124 ++ .../ticxo/modelengine/v1_21_R7/NMSFields.java | 59 + .../v1_21_R7/NMSHandler_v1_21_R7.java | 231 +++ .../modelengine/v1_21_R7/NMSMethods.java | 49 + .../v1_21_R7/entity/EntityContainer.java | 60 + .../v1_21_R7/entity/EntityHandlerImpl.java | 843 +++++++++++ .../v1_21_R7/entity/EntityMetadataID.java | 37 + .../v1_21_R7/entity/EntityUtils.java | 33 + .../v1_21_R7/entity/OcclusionClipContext.java | 116 ++ .../v1_21_R7/entity/TrackedEntityImpl.java | 333 +++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 152 ++ .../entity/controller/MoveControlWrapper.java | 272 ++++ .../entity/hitbox/HitboxEntityImpl.java | 271 ++++ .../v1_21_R7/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 457 ++++++ .../v1_21_R7/network/NetworkHandlerImpl.java | 141 ++ .../PatchedServerGamePacketListener.java | 439 ++++++ .../ServerboundInteractPacketWrapper.java | 75 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v1_21_R7/network/utils/Bundler.java | 65 + .../v1_21_R7/network/utils/NetworkUtils.java | 354 +++++ .../network/utils/PacketInterceptor.java | 84 ++ .../v1_21_R7/network/utils/Packets.java | 64 + .../parser/behavior/HeldItemParser.java | 186 +++ .../v1_21_R7/parser/behavior/LeashParser.java | 158 ++ .../v1_21_R7/parser/behavior/MountParser.java | 197 +++ .../parser/behavior/NameTagParser.java | 184 +++ .../parser/behavior/SegmentParser.java | 205 +++ .../parser/behavior/SubHitboxParser.java | 148 ++ .../v1_21_R7/parser/model/DisplayParser.java | 789 ++++++++++ .../v1_21_R7/parser/vfx/VFXDisplayParser.java | 124 ++ .../ticxo/modelengine/v26_1/NMSFields.java | 55 + .../modelengine/v26_1/NMSHandler_v26_1.java | 231 +++ .../ticxo/modelengine/v26_1/NMSMethods.java | 49 + .../v26_1/entity/EntityContainer.java | 60 + .../v26_1/entity/EntityHandlerImpl.java | 821 +++++++++++ .../v26_1/entity/EntityMetadataID.java | 37 + .../modelengine/v26_1/entity/EntityUtils.java | 33 + .../v26_1/entity/OcclusionClipContext.java | 116 ++ .../v26_1/entity/TrackedEntityImpl.java | 333 +++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 152 ++ .../entity/controller/MoveControlWrapper.java | 272 ++++ .../v26_1/entity/hitbox/HitboxEntityImpl.java | 288 ++++ .../modelengine/v26_1/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 474 ++++++ .../v26_1/network/NetworkHandlerImpl.java | 139 ++ .../PatchedServerGamePacketListener.java | 389 +++++ .../network/patch/RelayedPacketWrapper.java | 24 + .../patch/ServerboundAttackPacketWrapper.java | 28 + .../ServerboundInteractPacketWrapper.java | 49 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v26_1/network/utils/Bundler.java | 65 + .../v26_1/network/utils/NetworkUtils.java | 354 +++++ .../network/utils/PacketInterceptor.java | 89 ++ .../v26_1/network/utils/Packets.java | 64 + .../v26_1/parser/behavior/HeldItemParser.java | 186 +++ .../v26_1/parser/behavior/LeashParser.java | 158 ++ .../v26_1/parser/behavior/MountParser.java | 197 +++ .../v26_1/parser/behavior/NameTagParser.java | 184 +++ .../v26_1/parser/behavior/SegmentParser.java | 205 +++ .../parser/behavior/SubHitboxParser.java | 148 ++ .../v26_1/parser/model/DisplayParser.java | 791 ++++++++++ .../v26_1/parser/vfx/VFXDisplayParser.java | 124 ++ .../ticxo/modelengine/v26_2/NMSFields.java | 56 + .../modelengine/v26_2/NMSHandler_v26_2.java | 225 +++ .../ticxo/modelengine/v26_2/NMSMethods.java | 48 + .../v26_2/entity/EntityContainer.java | 60 + .../v26_2/entity/EntityHandlerImpl.java | 845 +++++++++++ .../v26_2/entity/EntityMetadataID.java | 37 + .../modelengine/v26_2/entity/EntityUtils.java | 33 + .../v26_2/entity/OcclusionClipContext.java | 116 ++ .../v26_2/entity/TrackedEntityImpl.java | 333 +++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 152 ++ .../entity/controller/MoveControlWrapper.java | 272 ++++ .../v26_2/entity/hitbox/HitboxEntityImpl.java | 288 ++++ .../modelengine/v26_2/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 474 ++++++ .../v26_2/network/NetworkHandlerImpl.java | 139 ++ .../PatchedServerGamePacketListener.java | 389 +++++ .../network/patch/RelayedPacketWrapper.java | 24 + .../patch/ServerboundAttackPacketWrapper.java | 28 + .../ServerboundInteractPacketWrapper.java | 49 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v26_2/network/utils/Bundler.java | 65 + .../v26_2/network/utils/NetworkUtils.java | 362 +++++ .../network/utils/PacketInterceptor.java | 89 ++ .../v26_2/network/utils/Packets.java | 64 + .../v26_2/parser/behavior/HeldItemParser.java | 186 +++ .../v26_2/parser/behavior/LeashParser.java | 158 ++ .../v26_2/parser/behavior/MountParser.java | 197 +++ .../v26_2/parser/behavior/NameTagParser.java | 184 +++ .../v26_2/parser/behavior/SegmentParser.java | 205 +++ .../parser/behavior/SubHitboxParser.java | 148 ++ .../v26_2/parser/model/DisplayParser.java | 791 ++++++++++ .../v26_2/parser/vfx/VFXDisplayParser.java | 124 ++ .../ticxo/modelengine/v26_3/NMSFields.java | 56 + .../modelengine/v26_3/NMSHandler_v26_3.java | 225 +++ .../ticxo/modelengine/v26_3/NMSMethods.java | 48 + .../v26_3/entity/EntityContainer.java | 60 + .../v26_3/entity/EntityHandlerImpl.java | 832 +++++++++++ .../v26_3/entity/EntityMetadataID.java | 37 + .../modelengine/v26_3/entity/EntityUtils.java | 33 + .../v26_3/entity/OcclusionClipContext.java | 116 ++ .../v26_3/entity/TrackedEntityImpl.java | 333 +++++ .../BodyRotationControlWrapper.java | 233 +++ .../entity/controller/LookControlWrapper.java | 145 ++ .../entity/controller/MoveControlWrapper.java | 272 ++++ .../v26_3/entity/hitbox/HitboxEntityImpl.java | 288 ++++ .../modelengine/v26_3/entity/hitbox/OBB.java | 87 ++ .../AmphibiousNavigationWrapper.java | 87 ++ .../navigation/FlyingNavigationWrapper.java | 81 + .../navigation/GroundNavigationWrapper.java | 81 + .../WallClimberNavigationWrapper.java | 81 + .../WaterBoundNavigationWrapper.java | 78 + .../network/ModelEngineChannelHandler.java | 474 ++++++ .../v26_3/network/NetworkHandlerImpl.java | 139 ++ .../PatchedServerGamePacketListener.java | 392 +++++ .../network/patch/RelayedPacketWrapper.java | 24 + .../patch/ServerboundAttackPacketWrapper.java | 28 + .../ServerboundInteractPacketWrapper.java | 49 + .../network/utils/BulkEntityDataEncoder.java | 148 ++ .../v26_3/network/utils/Bundler.java | 65 + .../v26_3/network/utils/NetworkUtils.java | 356 +++++ .../network/utils/PacketInterceptor.java | 89 ++ .../v26_3/network/utils/Packets.java | 64 + .../v26_3/parser/behavior/HeldItemParser.java | 186 +++ .../v26_3/parser/behavior/LeashParser.java | 158 ++ .../v26_3/parser/behavior/MountParser.java | 197 +++ .../v26_3/parser/behavior/NameTagParser.java | 184 +++ .../v26_3/parser/behavior/SegmentParser.java | 205 +++ .../parser/behavior/SubHitboxParser.java | 148 ++ .../v26_3/parser/model/DisplayParser.java | 791 ++++++++++ .../v26_3/parser/vfx/VFXDisplayParser.java | 124 ++ settings.gradle.kts | 24 + 1072 files changed, 160209 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 api/build.gradle.kts create mode 100644 api/src/main/java/com/ticxo/modelengine/api/ModelEngineAPI.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/ServerInfo.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/AnimationHandlerRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/AnimationPropertyRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/BlueprintAnimation.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/ModelState.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/Timeline.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/handler/AnimationHandler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/handler/IPriorityHandler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/handler/IStateMachineHandler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/KeyframeInterpolator.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/PrePostInterpolator.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/ScriptInterpolator.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeType.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeTypeRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeTypes.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/DoubleData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/IKeyframeData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/KeyframeReaderRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/AbstractKeyframe.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/IVectorType.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/ScriptKeyframe.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/VectorKeyframe.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/property/IAnimationProperty.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/property/SimpleProperty.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/property/SubTickProperty.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotion.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotionDelta.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotionHandler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/script/ScriptReader.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/animation/script/ScriptReaderRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/command/AbstractCommand.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/BaseEntity.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/BukkitEntity.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/BukkitPlayer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/CullType.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/Dummy.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/DynamicBox.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/EntityDataTrackers.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/Hitbox.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/cull/BasicCulling.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/cull/ModelCuller.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/data/AbstractEntityData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/data/BukkitEntityData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/data/DummyEntityData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/data/IEntityData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/entity/data/TrackingMap.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/ErrorCollector.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/ErrorIncompatibleBone.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/ErrorMissingBoneBehaviorData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/ErrorNoFaceCube.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/ErrorUnknownBoneBehavior.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/ErrorUnknownFormat.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/ErrorWrongBoneBehaviorDataType.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/IError.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarnBadAngle.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarnBadEyeHeight.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarnBadNamespace.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarnBadTexture.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarnBadTranslation.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarnBoneTooLarge.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarnBoxUV.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarnDuplicateTexture.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarnIncompatibleBoneBehavior.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarnMultipleAngle.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarnNoHitbox.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/error/WarningDuplicateBoneName.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/AbstractEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/AddModelEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/AnimationEndEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/AnimationPlayEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/BaseEntityInteractEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/BoneTransformReadEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/ModelDismountEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/ModelMountEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/ModelRegistrationEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/ModelSetupEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/RegisterBehaviorParserEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/RegisterParserEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/events/RemoveModelEvent.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/BaseItemEnum.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/ModelGenerator.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/assets/BlueprintTexture.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/assets/ItemModel.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/assets/ItemModelData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/assets/JavaDisplay.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/assets/JavaItemModel.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/assets/ModelAssets.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/assets/TintSource.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/blueprint/BlueprintBone.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/blueprint/ModelBlueprint.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/parser/ModelParser.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchBehaviorParser.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchDeserializer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchModel.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/LegacyDeserializer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/v5_0_Deserializer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/skin/LimbData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/skin/SkinGeneratorService.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/generator/skin/SkinSplitter.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/interaction/DynamicHitbox.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/interaction/InteractionTracker.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/lod/AnimationLODHandler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/lod/BoneSnapshotHandler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/menu/AbstractScreen.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/menu/ScreenManager.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/menu/Widget.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/ActiveModel.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/ModelRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/ModelUpdaters.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/ModeledEntity.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/PivotOverride.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/PivotOverrideRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/BoneBehaviorTypes.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/BoneItems.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/ManualAnimator.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/ModelBone.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/SimpleManualAnimator.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/AbstractBoneBehavior.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehavior.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorType.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/GlobalBehaviorData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/ProceduralType.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/AbstractBehaviorManager.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/BehaviorManager.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/LeashManager.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/MountData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/MountManager.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/render/BehaviorRenderer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/render/BehaviorRendererParser.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/render/DefaultRenderType.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/render/IRenderType.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/HeldItemRenderer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/LeashRenderer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/MountRenderer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/NameTagRenderer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/RenderQueues.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/SegmentRenderer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/SubHitboxRenderer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Ghost.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Head.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/type/HeldItem.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Leash.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Mount.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/type/NameTag.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/type/PlayerLimb.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Segment.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/type/SubHitbox.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/bone/type/UserLimb.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/limb/UserLimbCache.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/limb/UserLimbRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/operation/ModelOperation.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/operation/OperationResult.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/operation/OperationType.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayBone.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayFire.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayRenderer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/render/ModelRenderer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/model/render/ModelRendererParser.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/mount/MountControllerTypeRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/mount/MountPairManager.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountController.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerSupplier.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerType.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerTypes.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/AbstractMountController.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/FlyingMountController.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/WalkingMountController.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/NMSHandler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/RenderParsers.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/entity/AttributeAccessor.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/entity/EntityHandler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/entity/EntityState.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/entity/HitboxEntity.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/BodyRotationController.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/LookController.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/MoveController.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/MovementOverride.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/TrackedEntity.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/impl/DefaultBodyRotationController.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/impl/DummyTrackedEntity.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyBodyRotationController.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyLookController.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyMoveController.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/impl/TempTrackedEntity.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/network/CancelType.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/network/ClientDesyncMonitor.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/network/ModPlayerTracker.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/network/NetworkHandler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/network/PipelineWrapper.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/network/ProtectedPacket.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/network/ProtectedPacketUnpacker.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/nms/ui/AnvilHandler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/CompatibilityManager.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/MemoizeSupplier.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/MiscUtils.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/MojangAPI.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/OffsetMode.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/Profiler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/RaceConditionUtil.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/ReflectionUtils.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/RunnableGroup.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/StepFlag.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/TFile.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/callback/Callback.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigCache.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigManager.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigProperty.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/config/DebugToggle.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/config/Property.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/CachedImmutableMap.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/ComponentUtil.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/ConstSet.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/GSONUtils.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/ItemUtils.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/NullableHashSet.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/PooledCollection.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/PositionCodec.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedAtomic.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedBoolean.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedDouble.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedFloat.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedInt.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/ResourceLocation.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/Triple.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/UpdateScheme.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/interpolator/BasicInterpolator.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/interpolator/Interpolator.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/io/DataIO.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/io/SavedData.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/CollectionDataTracker.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/DataTracker.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/FloatDataTracker.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/MapDataTracker.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/QuaternionfDataTracker.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/UpdateDataTracker.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/Vector3fDataTracker.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/logger/LogColor.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/logger/TLogger.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/math/Axis.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/math/Box.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/math/ColorHelper.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/math/Direction.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/math/Easing.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/math/OrientedBoundingBox.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/math/SafeTransform.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/math/TMath.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/math/Transform.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/meta/IMetaHolder.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/meta/MetadataRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/promise/AbstractFoliaPromise.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/promise/AbstractPromise.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/promise/EntityPromise.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/promise/GlobalPromise.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/promise/LegacyPromise.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/promise/Promise.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/promise/RegionPromise.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/registry/TRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/registry/TUnaryRegistry.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/resourcepack/ResourcePackFeature.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/resourcepack/ResourcePackVersion.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/BukkitPlatformScheduler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/BukkitPlatformTask.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/FoliaPlatformScheduler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/FoliaPlatformTask.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/PlatformScheduler.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/PlatformTask.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/state/StateMachine.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/state/StateNode.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/ticker/AbstractLoadBalancer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/ticker/AsyncTaskExecutor.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/ticker/DualTicker.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/ticker/LoadBalancer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/ticker/PseudoThread.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/utils/ticker/Task.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/vfx/VFX.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/vfx/VFXUpdater.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXDisplayRenderer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXRenderer.java create mode 100644 api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXRendererParser.java create mode 100644 build.gradle.kts create mode 100644 core/build.gradle.kts create mode 100644 core/src/main/java/com/ticxo/modelengine/core/ModelEngine.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/animation/handler/PriorityHandler.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/animation/handler/StateMachineHandler.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/animation/script/ModelEngineScriptReader.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/citizens/BugTrait.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/citizens/CitizensCommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/citizens/ModelTrait.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/MECommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/ModelOptionParser.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/sub/DebugCommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/sub/DisguiseCommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/sub/MenuCommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/sub/PluginHealthCommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/sub/ReloadCommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/sub/ResyncCommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/sub/SummonCommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/sub/TestCommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/sub/ToggleLODCommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/command/sub/UndisguiseCommand.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/data/DataUpdater.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/data/V3Data.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/BaseItemManager.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/ModelCacheGroup.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/ModelGeneratorImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/ModelIdCache.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/PaletteImageWriter.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/atlas/Atlas.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/atlas/AtlasManager.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/java/BaseItem.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/java/BaseItemTransformer.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/BlockbenchParser.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/json/DefaultBehaviorParser.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/json/MCMetaDeserializer.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/processed/ProcessedBone.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/skin/FaceMapper.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/skin/MineSkinGeneratorService.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/skin/PlayerMapper.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/skin/SkinSplitterImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/util/HashedVector3d.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/util/IllegalRotationSolver.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/util/ItemGroup.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/util/PlaneGroup.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/generator/util/RotationSolver.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/javasupport/Java21Access.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/javasupport/Java25Access.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/libsdisguises/DisguiseCompatibility.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/listener/ChatListener.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/listener/EntityListener.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/listener/InventoryListener.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/listener/PlayerListener.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/listener/WorldListener.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/SelectionManager.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/screen/AddModelScreen.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/screen/EditEntityScreen.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/screen/EditModelScreen.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/screen/NavigationScreen.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/screen/SpawnModelScreen.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/widget/BasicItemWidget.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/widget/BorderWidget.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/widget/CloseWidget.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/widget/CompositeWidget.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/widget/PaginatorWidget.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/widget/TabWidget.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/menu/widget/page/AbstractModelButton.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/misc/Alternator.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/misc/Cardinal.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/ActiveModelImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/BoneSequencer.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/ModeledEntityImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/ModelBoneImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/AbstractSegmentImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/Dummy.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/GhostImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeadForcedImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeadImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeldItemImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/LeashImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/MountImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/NameTagImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/PlayerLimbImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/SegmentImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/SubHitboxImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/TailImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/UserLimbImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/LeashManagerImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/MountDataImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/MountManagerImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/render/AbstractBehaviorRenderer.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/render/HeldItemRendererImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/render/LeashRendererImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/render/MountRendererImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/render/NameTagRendererImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/render/SegmentRendererImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/bone/render/SubHitboxRendererImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayBoneImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayFireImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayRendererImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/vfx/VFXImpl.java create mode 100644 core/src/main/java/com/ticxo/modelengine/core/vfx/render/VFXDisplayRendererImpl.java create mode 100644 core/src/main/resources/config.yml create mode 100644 core/src/main/resources/internal/alex_mapped.bbmodel create mode 100644 core/src/main/resources/internal/internal_fire.bbmodel create mode 100644 core/src/main/resources/internal/player_model.bbmodel create mode 100644 core/src/main/resources/internal/steve_mapped.bbmodel create mode 100644 core/src/main/resources/pack/assets/minecraft/shaders/core/entity.fsh create mode 100644 core/src/main/resources/pack/assets/minecraft/shaders/core/entity.vsh create mode 100644 core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.fsh create mode 100644 core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.json create mode 100644 core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.vsh create mode 100644 core/src/main/resources/pack/assets/minecraft/shaders/include/player_shader.glsl create mode 100644 core/src/main/resources/pack/assets/modelengine/items/player_head.json create mode 100644 core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/head.json create mode 100644 core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/left_arm.json create mode 100644 core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/left_leg.json create mode 100644 core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/right_arm.json create mode 100644 core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/right_leg.json create mode 100644 core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/slim_left.json create mode 100644 core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/slim_right.json create mode 100644 core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/torso.json create mode 100644 core/src/main/resources/pack/colorable/filled_map.json create mode 100644 core/src/main/resources/pack/colorable/leather_boots.json create mode 100644 core/src/main/resources/pack/colorable/leather_chestplate.json create mode 100644 core/src/main/resources/pack/colorable/leather_horse_armor.json create mode 100644 core/src/main/resources/pack/colorable/leather_leggings.json create mode 100644 core/src/main/resources/pack/colorable/lingering_potion.json create mode 100644 core/src/main/resources/pack/colorable/potion.json create mode 100644 core/src/main/resources/pack/colorable/splash_potion.json create mode 100644 core/src/main/resources/pack/colorable/tipped_arrow.json create mode 100644 core/src/main/resources/pack/modelengine_1_19_4/assets/minecraft/models/item/player_head.json create mode 100644 core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/entity.fsh create mode 100644 core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/entity.vsh create mode 100644 core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.fsh create mode 100644 core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.json create mode 100644 core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.vsh create mode 100644 core/src/main/resources/pack/modelengine_1_21_4/assets/modelengine/items/player_head.json create mode 100644 core/src/main/resources/pack/modelengine_1_21_5/assets/minecraft/shaders/core/entity.fsh create mode 100644 core/src/main/resources/pack/modelengine_1_21_5/assets/minecraft/shaders/core/entity.vsh create mode 100644 core/src/main/resources/pack/modelengine_1_21_6/assets/minecraft/shaders/core/entity.fsh create mode 100644 core/src/main/resources/pack/modelengine_1_21_6/assets/minecraft/shaders/core/entity.vsh create mode 100644 core/src/main/resources/pack/modelengine_26_1/assets/minecraft/shaders/core/entity.fsh create mode 100644 core/src/main/resources/pack/modelengine_26_1/assets/minecraft/shaders/core/entity.vsh create mode 100644 core/src/main/resources/pack/modelengine_26_2/assets/minecraft/shaders/core/entity.fsh create mode 100644 core/src/main/resources/pack/modelengine_26_2/assets/minecraft/shaders/core/entity.vsh create mode 100644 core/src/main/resources/pack/pack.mcmeta create mode 100644 core/src/main/resources/pack/pack.png create mode 100644 core/src/main/resources/plugin.yml create mode 100644 core21/build.gradle.kts create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/Java21Helper.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/MythicUtils.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/animation/MythicScriptReader.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/AuraAttachment.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/FakeEntity.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MEGModel.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ModelEngineSupportImpl.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MythicCompatibility.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MythicMountController.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileBullet.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileData.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileEntity.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HasModelCondition.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HitboxCondition.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HitboxIsSubHitboxCondition.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/IsDrivingModelCondition.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/IsRidingModelCondition.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/ModelHasDriverCondition.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/ModelHasPassengerCondition.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/AnimateModelMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/BillboardMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/BrightnessMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ChangeParentMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ChangePartMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/CyclePartsMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/EnchantMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/GlowMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ModelSkinMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/PartVisibilityMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/SegmentMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/TintMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/JumpMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/MoveMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/NoFallMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/SyncYawMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/disguise/DisguiseMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/disguise/UndisguiseMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/BodyRotationMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/ConfigureCullMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/ModelMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/PairModelMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/PetrifyMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/hitbox/BindHitboxMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/hitbox/ConfigureHitboxMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/item/LinkItemBoneMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/item/SetItemModelMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/leash/LeashMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/leash/LeashSelfMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/DefaultStateMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/LockHeadMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/LockModelRotationMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/ModifyStateMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RemapModelMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RendererInitMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RootMotionMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/ScaleMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/StateMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/StateToggleMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/SubModelMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/SwapEntityMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/DismountAllMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/DismountModelMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/MountModelMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/nametag/SetNametagMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/nametag/SetNametagVisibilityMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXBrightnessMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXChangeModelMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXEnchantMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetPositionMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetRotationMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetScaleMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetPositionMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetRotationMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetScaleMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetVisibilityMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXTintMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/placeholders/CasterModelRotationPlaceholder.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelDriverTargeter.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelPartTargeter.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelPassengersTargeter.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/MountedModelTargeter.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/ModelEngineComponentRegistry.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicCondition.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicMechanic.java create mode 100644 core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicTargeter.java create mode 100644 core25/build.gradle.kts create mode 100644 core25/src/main/java/com/ticxo/modelengine/core25/Java25Helper.java create mode 100644 gradle.properties create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 libs/mineskin-java-client-3.2.1-SNAPSHOT.jar create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/NMSFields.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/NMSHandler_v1_19_R3.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/NMSMethods.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityHandlerImpl.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityMetadataID.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityUtils.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/OcclusionClipContext.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/TrackedEntityImpl.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/hitbox/OBB.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/NetworkHandlerImpl.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/Bundler.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/NetworkUtils.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/PacketInterceptor.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/Packets.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/LeashParser.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/MountParser.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/NameTagParser.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/SegmentParser.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/model/DisplayParser.java create mode 100644 nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSFields.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSHandler_v1_20_R1.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSMethods.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityHandlerImpl.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityMetadataID.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityUtils.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/OcclusionClipContext.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/TrackedEntityImpl.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/hitbox/OBB.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/NetworkHandlerImpl.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/Bundler.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/NetworkUtils.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/PacketInterceptor.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/Packets.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/LeashParser.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/MountParser.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/NameTagParser.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/SegmentParser.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/model/DisplayParser.java create mode 100644 nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSFields.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSHandler_v1_20_R2.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSMethods.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityHandlerImpl.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityMetadataID.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityUtils.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/OcclusionClipContext.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/TrackedEntityImpl.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/hitbox/OBB.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/NetworkHandlerImpl.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/Bundler.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/NetworkUtils.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/PacketInterceptor.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/Packets.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/LeashParser.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/MountParser.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/NameTagParser.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/SegmentParser.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/model/DisplayParser.java create mode 100644 nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSFields.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSHandler_v1_20_R3.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSMethods.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityHandlerImpl.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityMetadataID.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityUtils.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/OcclusionClipContext.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/TrackedEntityImpl.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/hitbox/OBB.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/NetworkHandlerImpl.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/Bundler.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/NetworkUtils.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/PacketInterceptor.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/Packets.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/LeashParser.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/MountParser.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/NameTagParser.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/SegmentParser.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/model/DisplayParser.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/ui/AnvilHandlerImpl.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSFields.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSHandler_v1_20_R4.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSMethods.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityContainer.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityHandlerImpl.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityMetadataID.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityUtils.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/OcclusionClipContext.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/TrackedEntityImpl.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/hitbox/OBB.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/NetworkHandlerImpl.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/Bundler.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/NetworkUtils.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/PacketInterceptor.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/Packets.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/LeashParser.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/MountParser.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/NameTagParser.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/SegmentParser.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/model/DisplayParser.java create mode 100644 nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSFields.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSHandler_v1_21_R1.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSMethods.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityContainer.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityHandlerImpl.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityMetadataID.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityUtils.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/OcclusionClipContext.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/TrackedEntityImpl.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/hitbox/OBB.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/NetworkHandlerImpl.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/Bundler.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/NetworkUtils.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/PacketInterceptor.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/Packets.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/LeashParser.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/MountParser.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/NameTagParser.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/SegmentParser.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/model/DisplayParser.java create mode 100644 nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSFields.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSHandler_v1_21_R2.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSMethods.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityContainer.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityHandlerImpl.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityMetadataID.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityUtils.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/OcclusionClipContext.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/TrackedEntityImpl.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/hitbox/OBB.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/NetworkHandlerImpl.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/Bundler.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/NetworkUtils.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/PacketInterceptor.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/Packets.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/LeashParser.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/MountParser.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/NameTagParser.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/SegmentParser.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/model/DisplayParser.java create mode 100644 nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSFields.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSHandler_v1_21_R3.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSMethods.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityContainer.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityHandlerImpl.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityMetadataID.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityUtils.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/OcclusionClipContext.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/TrackedEntityImpl.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/hitbox/OBB.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/NetworkHandlerImpl.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/Bundler.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/NetworkUtils.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/PacketInterceptor.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/Packets.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/LeashParser.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/MountParser.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/NameTagParser.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/SegmentParser.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/model/DisplayParser.java create mode 100644 nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSFields.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSHandler_v1_21_R4.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSMethods.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityContainer.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityHandlerImpl.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityMetadataID.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityUtils.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/OcclusionClipContext.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/TrackedEntityImpl.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/hitbox/OBB.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/NetworkHandlerImpl.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/Bundler.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/NetworkUtils.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/PacketInterceptor.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/Packets.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/LeashParser.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/MountParser.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/NameTagParser.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/SegmentParser.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/model/DisplayParser.java create mode 100644 nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSFields.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSHandler_v1_21_R5.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSMethods.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityContainer.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityHandlerImpl.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityMetadataID.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityUtils.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/OcclusionClipContext.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/TrackedEntityImpl.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/hitbox/OBB.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/NetworkHandlerImpl.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/Bundler.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/NetworkUtils.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/PacketInterceptor.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/Packets.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/LeashParser.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/MountParser.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/NameTagParser.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/SegmentParser.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/model/DisplayParser.java create mode 100644 nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSFields.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSHandler_v1_21_R6.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSMethods.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityContainer.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityHandlerImpl.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityMetadataID.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityUtils.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/OcclusionClipContext.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/TrackedEntityImpl.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/hitbox/OBB.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/NetworkHandlerImpl.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/Bundler.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/NetworkUtils.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/PacketInterceptor.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/Packets.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/LeashParser.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/MountParser.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/NameTagParser.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/SegmentParser.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/model/DisplayParser.java create mode 100644 nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSFields.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSHandler_v1_21_R7.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSMethods.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityContainer.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityHandlerImpl.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityMetadataID.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityUtils.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/OcclusionClipContext.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/TrackedEntityImpl.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/LookControlWrapper.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/MoveControlWrapper.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/hitbox/OBB.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/ModelEngineChannelHandler.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/NetworkHandlerImpl.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/Bundler.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/NetworkUtils.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/PacketInterceptor.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/Packets.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/HeldItemParser.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/LeashParser.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/MountParser.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/NameTagParser.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/SegmentParser.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/SubHitboxParser.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/model/DisplayParser.java create mode 100644 nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSFields.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSHandler_v26_1.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSMethods.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityContainer.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityHandlerImpl.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityMetadataID.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityUtils.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/OcclusionClipContext.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/TrackedEntityImpl.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/LookControlWrapper.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/MoveControlWrapper.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/hitbox/OBB.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/ModelEngineChannelHandler.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/NetworkHandlerImpl.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/RelayedPacketWrapper.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/ServerboundAttackPacketWrapper.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/Bundler.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/NetworkUtils.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/PacketInterceptor.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/Packets.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/HeldItemParser.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/LeashParser.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/MountParser.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/NameTagParser.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/SegmentParser.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/SubHitboxParser.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/model/DisplayParser.java create mode 100644 nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSFields.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSHandler_v26_2.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSMethods.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityContainer.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityHandlerImpl.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityMetadataID.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityUtils.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/OcclusionClipContext.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/TrackedEntityImpl.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/LookControlWrapper.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/MoveControlWrapper.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/hitbox/OBB.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/ModelEngineChannelHandler.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/NetworkHandlerImpl.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/RelayedPacketWrapper.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/ServerboundAttackPacketWrapper.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/Bundler.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/NetworkUtils.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/PacketInterceptor.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/Packets.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/HeldItemParser.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/LeashParser.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/MountParser.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/NameTagParser.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/SegmentParser.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/SubHitboxParser.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/model/DisplayParser.java create mode 100644 nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/vfx/VFXDisplayParser.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSFields.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSHandler_v26_3.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSMethods.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityContainer.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityHandlerImpl.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityMetadataID.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityUtils.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/OcclusionClipContext.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/TrackedEntityImpl.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/BodyRotationControlWrapper.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/LookControlWrapper.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/MoveControlWrapper.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/hitbox/HitboxEntityImpl.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/hitbox/OBB.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/AmphibiousNavigationWrapper.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/FlyingNavigationWrapper.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/GroundNavigationWrapper.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/WallClimberNavigationWrapper.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/WaterBoundNavigationWrapper.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/ModelEngineChannelHandler.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/NetworkHandlerImpl.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/PatchedServerGamePacketListener.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/RelayedPacketWrapper.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/ServerboundAttackPacketWrapper.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/ServerboundInteractPacketWrapper.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/BulkEntityDataEncoder.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/Bundler.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/NetworkUtils.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/PacketInterceptor.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/Packets.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/HeldItemParser.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/LeashParser.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/MountParser.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/NameTagParser.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/SegmentParser.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/SubHitboxParser.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/model/DisplayParser.java create mode 100644 nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/vfx/VFXDisplayParser.java create mode 100644 settings.gradle.kts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d5d24a9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.gradle/ +build/ +*/build/ +nms/*/build/ +.idea/ +*.iml diff --git a/README.md b/README.md new file mode 100644 index 0000000..bf0ab3c --- /dev/null +++ b/README.md @@ -0,0 +1,58 @@ +

+ Version R4.2.0 + Java 17 | 21 | 25 + Gradle 9.9.1 + Paper 1.19.4 - 26.3 +

+ +## 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. diff --git a/api/build.gradle.kts b/api/build.gradle.kts new file mode 100644 index 0000000..500eaec --- /dev/null +++ b/api/build.gradle.kts @@ -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 } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/ModelEngineAPI.java b/api/src/main/java/com/ticxo/modelengine/api/ModelEngineAPI.java new file mode 100644 index 0000000..e463bb9 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/ModelEngineAPI.java @@ -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 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 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 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 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> baseEntitySupplier) { + ModeledEntity model = getModeledEntity(uuid); + return model != null ? model : createModeledEntity(baseEntitySupplier.get(), null); + } + + public static ModeledEntity getOrCreateModeledEntity(UUID uuid, Supplier> baseEntitySupplier, Consumer 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 rendererSupplier, Function 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 rendererSupplier, Function 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 consumer) { + return createVFX(base, consumer, null); + } + + public static VFX createVFX(Entity base, Consumer consumer, Function 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 consumer) { + return createVFX(base, consumer, null); + } + + public static VFX createVFX(BaseEntity base, Consumer consumer, Function 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 var2); + + public abstract ActiveModel createActiveModelImpl( + ModelBlueprint var1, Function var2, Function var3 + ); + + public abstract VFX createVFXImpl(BaseEntity var1, Function var2, Consumer 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 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/ServerInfo.java b/api/src/main/java/com/ticxo/modelengine/api/ServerInfo.java new file mode 100644 index 0000000..8bbf00a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/ServerInfo.java @@ -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 ONLINE_PLAYERS = new HashSet<>(); + private static volatile ImmutableSet 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 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; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/AnimationHandlerRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/animation/AnimationHandlerRegistry.java new file mode 100644 index 0000000..5d1a492 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/AnimationHandlerRegistry.java @@ -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> { + public AnimationHandler createHandler(ActiveModel model, SavedData data) { + String id = data.getString("id"); + return id != null ? this.get(id).apply(model, data) : null; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/AnimationPropertyRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/animation/AnimationPropertyRegistry.java new file mode 100644 index 0000000..5f47816 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/AnimationPropertyRegistry.java @@ -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> { + public IAnimationProperty createAnimationProperty(AnimationHandler handler, SavedData data) { + String id = data.getString("id"); + return id != null ? this.get(id).apply(handler, data) : null; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/BlueprintAnimation.java b/api/src/main/java/com/ticxo/modelengine/api/animation/BlueprintAnimation.java new file mode 100644 index 0000000..3e6ff99 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/BlueprintAnimation.java @@ -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 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 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, ?> interpolator = timeline.getInterpolator((KeyframeType, ?>)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 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; + } + } + } + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/ModelState.java b/api/src/main/java/com/ticxo/modelengine/api/animation/ModelState.java new file mode 100644 index 0000000..49bc387 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/ModelState.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/Timeline.java b/api/src/main/java/com/ticxo/modelengine/api/animation/Timeline.java new file mode 100644 index 0000000..1b1f0f1 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/Timeline.java @@ -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, 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 , DATA> KeyframeInterpolator getInterpolator(KeyframeType type) { + KeyframeInterpolator, ?> cached = (KeyframeInterpolator, ?>)this.getCached(type); + if (cached != null) { + return (KeyframeInterpolator)cached; + } else { + KeyframeInterpolator, ?> interpolator = (KeyframeInterpolator, ?>)this.interpolators + .get(type); + if (interpolator == null) { + interpolator = (KeyframeInterpolator, ?>)this.interpolators + .computeIfAbsent(type, keyframeType -> keyframeType.createInterpolator(this)); + } + + this.setCached(type, interpolator); + return (KeyframeInterpolator)interpolator; + } + } + + public , DATA> KEY getKeyframe(float time, KeyframeType type) { + KeyframeInterpolator 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/handler/AnimationHandler.java b/api/src/main/java/com/ticxo/modelengine/api/animation/handler/AnimationHandler.java new file mode 100644 index 0000000..70934a4 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/handler/AnimationHandler.java @@ -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 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 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() + + ")"; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/handler/IPriorityHandler.java b/api/src/main/java/com/ticxo/modelengine/api/animation/handler/IPriorityHandler.java new file mode 100644 index 0000000..ce3f15e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/handler/IPriorityHandler.java @@ -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 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"; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/handler/IStateMachineHandler.java b/api/src/main/java/com/ticxo/modelengine/api/animation/handler/IStateMachineHandler.java new file mode 100644 index 0000000..4578de2 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/handler/IStateMachineHandler.java @@ -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"; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/KeyframeInterpolator.java b/api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/KeyframeInterpolator.java new file mode 100644 index 0000000..265f627 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/KeyframeInterpolator.java @@ -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, OUT> extends TreeMap { + protected KeyframeInterpolator.Interpolation interpolateFunc; + protected Supplier defaultValue = null; + + public KeyframeInterpolator setInterpolateFunc(KeyframeInterpolator.Interpolation interpolateFunc) { + this.interpolateFunc = interpolateFunc; + return this; + } + + public KeyframeInterpolator setDefaultValue(Supplier 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 lastEntry = this.floorEntry(time); + if (lastEntry != null && Float.compare(lastEntry.getKey(), time) == 0) { + return lastEntry.getValue().getValue(0, property); + } else { + Entry 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, 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 interpolator; + + public Context( + float prevKey, float nextKey, IN prevFrame, IN nextFrame, IAnimationProperty property, ModelBone bone, KeyframeInterpolator 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, OUT> { + OUT interpolate(KeyframeInterpolator.Context var1, OUT var2, OUT var3, float var4); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/PrePostInterpolator.java b/api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/PrePostInterpolator.java new file mode 100644 index 0000000..d4eeb5d --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/PrePostInterpolator.java @@ -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, OUT> extends KeyframeInterpolator { + private final BiFunction derivativeFunc; + private final BiConsumer, IN> finalizerFunc; + + public PrePostInterpolator( + KeyframeInterpolator.Interpolation interpolateFunc, + BiConsumer, IN> finalizerFunc, + BiFunction derivativeFunc + ) { + this(interpolateFunc, finalizerFunc, derivativeFunc, () -> null); + } + + public PrePostInterpolator( + KeyframeInterpolator.Interpolation interpolateFunc, + BiConsumer, IN> finalizerFunc, + BiFunction derivativeFunc, + Supplier 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 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 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); + } + } + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/ScriptInterpolator.java b/api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/ScriptInterpolator.java new file mode 100644 index 0000000..4a3536f --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/interpolator/ScriptInterpolator.java @@ -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, OUT> extends KeyframeInterpolator { + private final Supplier supplier; + private final BiConsumer 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 supplier, BiConsumer combiner) { + this.supplier = supplier; + this.combiner = combiner; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeType.java b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeType.java new file mode 100644 index 0000000..3679196 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeType.java @@ -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, DATA> { + private final String id; + private final Supplier keyframeSupplier; + private final Function> interpolatorSupplier; + private final Map, KeyframeType.ModelUpdater> modelUpdaters; + private final Map, 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 keyframeSupplier, + Function> interpolatorSupplier, + Map, KeyframeType.ModelUpdater> modelUpdaters, + Map, 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 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 getKeyframeSupplier() { + return this.keyframeSupplier; + } + + public Function> getInterpolatorSupplier() { + return this.interpolatorSupplier; + } + + public Map, KeyframeType.ModelUpdater> getModelUpdaters() { + return this.modelUpdaters; + } + + public Map, 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, DATA> { + private final String id; + private final Supplier keyframeSupplier; + private final Map, KeyframeType.ModelUpdater> modelUpdaters = new HashMap<>(); + private final Map, KeyframeType.BoneUpdater> boneUpdaters = new HashMap<>(); + private Function> interpolatorSupplier = blueprintAnimation -> new KeyframeInterpolator<>(); + private boolean global; + + public static , DATA> KeyframeType.Builder of(String id, Supplier keyframeSupplier) { + return new KeyframeType.Builder<>(id, keyframeSupplier); + } + + public KeyframeType.Builder interpolator(Function> interpolatorSupplier) { + this.interpolatorSupplier = interpolatorSupplier; + return this; + } + + public KeyframeType.Builder registerModelUpdater(Class handlerClass, KeyframeType.ModelUpdater updater) { + this.modelUpdaters.put(handlerClass, updater); + return this; + } + + public KeyframeType.Builder registerBoneUpdater(Class handlerClass, KeyframeType.BoneUpdater updater) { + this.boneUpdaters.put(handlerClass, updater); + return this; + } + + public KeyframeType.Builder global() { + this.global = true; + return this; + } + + public KeyframeType build() { + return new KeyframeType<>(this.id, this.keyframeSupplier, this.interpolatorSupplier, this.modelUpdaters, this.boneUpdaters, this.global); + } + + protected Builder(String id, Supplier keyframeSupplier) { + this.id = id; + this.keyframeSupplier = keyframeSupplier; + } + } + + @FunctionalInterface + public interface ModelUpdater { + void update(AnimationHandler var1, ActiveModel var2, Object... var3); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeTypeRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeTypeRegistry.java new file mode 100644 index 0000000..e314f2b --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeTypeRegistry.java @@ -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> { + private final Set keys = new LinkedHashSet<>(); + + public void registerKeyframeType(KeyframeType type) { + this.keys.add(type.getId()); + this.register(type.getId(), type); + } + + @Override + public Set getKeys() { + return this.keys; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeTypes.java b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeTypes.java new file mode 100644 index 0000000..fede850 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/KeyframeTypes.java @@ -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 POSITION = KeyframeType.Builder.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 ROTATION = KeyframeType.Builder.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 SCALE = KeyframeType.Builder.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> SCRIPT = KeyframeType.Builder.>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 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 nextControlEntry = ctx.interpolator.higherEntry(ctx.nextKey); + if (nextControlEntry == null) { + nextControlEntry = ctx.interpolator.lastEntry(); + } + + Entry 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 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 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 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()); + } + } + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/DoubleData.java b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/DoubleData.java new file mode 100644 index 0000000..394540d --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/DoubleData.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/IKeyframeData.java b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/IKeyframeData.java new file mode 100644 index 0000000..190578c --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/IKeyframeData.java @@ -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); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/KeyframeReaderRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/KeyframeReaderRegistry.java new file mode 100644 index 0000000..86a9dcd --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/data/KeyframeReaderRegistry.java @@ -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> { + 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 func : this.registry.values()) { + try { + return func.apply(value[0]); + } catch (Throwable var8) { + } + } + } else { + Function 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 func2 : this.registry.values()) { + try { + return func2.apply(data); + } catch (Throwable var9) { + } + } + } + } + + TLogger.warn(2, "------Unknown keyframe data: " + data); + return IKeyframeData.EMPTY; + } + } + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/AbstractKeyframe.java b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/AbstractKeyframe.java new file mode 100644 index 0000000..a5a72d8 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/AbstractKeyframe.java @@ -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 { + 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; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/IVectorType.java b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/IVectorType.java new file mode 100644 index 0000000..c6f40a5 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/IVectorType.java @@ -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); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/ScriptKeyframe.java b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/ScriptKeyframe.java new file mode 100644 index 0000000..2a45029 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/ScriptKeyframe.java @@ -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> { + private final List script = new ArrayList<>(); + + public List getValue(int index, IAnimationProperty property) { + return this.script; + } + + public List 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]); + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/VectorKeyframe.java b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/VectorKeyframe.java new file mode 100644 index 0000000..02f4077 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/keyframe/type/VectorKeyframe.java @@ -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 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/property/IAnimationProperty.java b/api/src/main/java/com/ticxo/modelengine/api/animation/property/IAnimationProperty.java new file mode 100644 index 0000000..95dd55a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/property/IAnimationProperty.java @@ -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 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/property/SimpleProperty.java b/api/src/main/java/com/ticxo/modelengine/api/animation/property/SimpleProperty.java new file mode 100644 index 0000000..d3da1ab --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/property/SimpleProperty.java @@ -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 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/property/SubTickProperty.java b/api/src/main/java/com/ticxo/modelengine/api/animation/property/SubTickProperty.java new file mode 100644 index 0000000..45b8b7a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/property/SubTickProperty.java @@ -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 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); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotion.java b/api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotion.java new file mode 100644 index 0000000..1894cda --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotion.java @@ -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)); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotionDelta.java b/api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotionDelta.java new file mode 100644 index 0000000..7960bc7 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotionDelta.java @@ -0,0 +1,6 @@ +package com.ticxo.modelengine.api.animation.rootmotion; + +import org.bukkit.util.Vector; + +public record RootMotionDelta(Vector delta, boolean onGround) { +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotionHandler.java b/api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotionHandler.java new file mode 100644 index 0000000..845ace9 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/rootmotion/RootMotionHandler.java @@ -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 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 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/script/ScriptReader.java b/api/src/main/java/com/ticxo/modelengine/api/animation/script/ScriptReader.java new file mode 100644 index 0000000..6699aae --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/script/ScriptReader.java @@ -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); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/animation/script/ScriptReaderRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/animation/script/ScriptReaderRegistry.java new file mode 100644 index 0000000..e86f803 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/animation/script/ScriptReaderRegistry.java @@ -0,0 +1,6 @@ +package com.ticxo.modelengine.api.animation.script; + +import com.ticxo.modelengine.api.utils.registry.TUnaryRegistry; + +public class ScriptReaderRegistry extends TUnaryRegistry { +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/command/AbstractCommand.java b/api/src/main/java/com/ticxo/modelengine/api/command/AbstractCommand.java new file mode 100644 index 0000000..556ea32 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/command/AbstractCommand.java @@ -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 subCommands = new HashMap<>(); + private final Map 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 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 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 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/BaseEntity.java b/api/src/main/java/com/ticxo/modelengine/api/entity/BaseEntity.java new file mode 100644 index 0000000..f41fd47 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/BaseEntity.java @@ -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 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 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)); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/BukkitEntity.java b/api/src/main/java/com/ticxo/modelengine/api/entity/BukkitEntity.java new file mode 100644 index 0000000..04f4167 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/BukkitEntity.java @@ -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 { + 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 set = livingEntity.getCollidableExemptions(); + if (set != null) { + if (flag) { + set.remove(entity.getUniqueId()); + } else { + set.add(entity.getUniqueId()); + } + } + } + }, null); + } else { + Set 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 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 exemptions = this.data.getCollidableExemptions(); + if (exemptions != null) { + data.putList("collide_exemption", exemptions); + } + } + + @Override + public void load(SavedData data) { + BaseEntity.super.load(data); + Set 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/BukkitPlayer.java b/api/src/main/java/com/ticxo/modelengine/api/entity/BukkitPlayer.java new file mode 100644 index 0000000..804cfd2 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/BukkitPlayer.java @@ -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; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/CullType.java b/api/src/main/java/com/ticxo/modelengine/api/entity/CullType.java new file mode 100644 index 0000000..90bdc93 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/CullType.java @@ -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; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/Dummy.java b/api/src/main/java/com/ticxo/modelengine/api/entity/Dummy.java new file mode 100644 index 0000000..02e9eab --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/Dummy.java @@ -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 implements BaseEntity { + protected final int entityId; + protected final UUID uuid; + protected final T original; + protected final DummyEntityData 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 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/DynamicBox.java b/api/src/main/java/com/ticxo/modelengine/api/entity/DynamicBox.java new file mode 100644 index 0000000..d24d680 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/DynamicBox.java @@ -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); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/EntityDataTrackers.java b/api/src/main/java/com/ticxo/modelengine/api/entity/EntityDataTrackers.java new file mode 100644 index 0000000..1bf0cff --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/EntityDataTrackers.java @@ -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 { + private final Map 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 entry : this.threads.entrySet()) { + entry.getValue().start(); + } + } + + public void end() { + for (Entry 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 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 dataTrackers = Maps.newConcurrentMap(); + private String id = "Unknown"; + private volatile int lastSize = 0; + private long timings; + private long verifiedEpoch = -1L; + private final Set 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 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 getDataTrackers() { + return this.dataTrackers; + } + + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + public long getTimings() { + return this.timings; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/Hitbox.java b/api/src/main/java/com/ticxo/modelengine/api/entity/Hitbox.java new file mode 100644 index 0000000..e00abe4 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/Hitbox.java @@ -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() + ")"; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/cull/BasicCulling.java b/api/src/main/java/com/ticxo/modelengine/api/entity/cull/BasicCulling.java new file mode 100644 index 0000000..c945f17 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/cull/BasicCulling.java @@ -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 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/cull/ModelCuller.java b/api/src/main/java/com/ticxo/modelengine/api/entity/cull/ModelCuller.java new file mode 100644 index 0000000..d4fe0a9 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/cull/ModelCuller.java @@ -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 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(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/data/AbstractEntityData.java b/api/src/main/java/com/ticxo/modelengine/api/entity/data/AbstractEntityData.java new file mode 100644 index 0000000..099189e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/data/AbstractEntityData.java @@ -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 glowingModel = new HashSet<>(); + private final Set glowingBone = new HashSet<>(); + private final Set 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 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/data/BukkitEntityData.java b/api/src/main/java/com/ticxo/modelengine/api/entity/data/BukkitEntityData.java new file mode 100644 index 0000000..c57d276 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/data/BukkitEntityData.java @@ -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 = QueuedAtomic.builder() + .value(() -> new Location(null, 0.0, 0.0, 0.0)) + .passer((a, b) -> b.set(a.get().clone())) + .build(); + protected final QueuedAtomic> passengers = QueuedAtomic.>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 = QueuedAtomic.builder() + .value(() -> new BoundingBox(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)) + .build(); + protected final Set syncTracking = new HashSet<>(); + private final TrackingMap trackingMap = new TrackingMap(); + protected final Map asyncTracking = this.trackingMap; + protected final Queue> startTrackingQueue = new ConcurrentLinkedQueue<>(); + protected final Set startTracking = new HashSet<>(); + protected final Queue> stopTrackingQueue = new ConcurrentLinkedQueue<>(); + protected final Set stopTracking = new HashSet<>(); + protected final Predicate 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 reuseTracking = new HashSet<>(); + private long lastTrackingVersion = -1L; + protected volatile Set 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 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 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 updatedTracking = this.getTracked().getTrackedPlayer(this.trackingPredicate, this.reuseTracking); + Queue startTrack = null; + Queue 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 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 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 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 getPassengers() { + return this.passengers.get(); + } + + @Override + public void markViewersDirty() { + TrackedEntity current = this.tracked; + if (current != null) { + current.markViewersDirty(); + } + } + + @Override + public Set getStartTracking() { + return ImmutableSet.copyOf(this.startTracking); + } + + public void resendTracking(UUID player) { + if (this.asyncTracking.containsKey(player)) { + Queue queue = new ConcurrentLinkedQueue<>(); + queue.add(player); + this.startTrackingQueue.add(queue); + } + } + + @Override + public Map getMutableTracking() { + return this.asyncTracking; + } + + @Override + public Map getTracking() { + return this.trackingMap.snapshot(); + } + + @Override + public Set 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/data/DummyEntityData.java b/api/src/main/java/com/ticxo/modelengine/api/entity/data/DummyEntityData.java new file mode 100644 index 0000000..ebebe8c --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/data/DummyEntityData.java @@ -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 extends AbstractEntityData { + protected final Dummy dummy; + protected final DummyTrackedEntity tracked; + protected final ModelCuller culler; + protected final Set syncTracking = new HashSet<>(); + private final TrackingMap trackingMap = new TrackingMap(); + protected final Map asyncTracking = this.trackingMap; + protected final Queue startTrackingQueue = new ConcurrentLinkedQueue<>(); + protected final Set startTracking = new HashSet<>(); + protected final Queue stopTrackingQueue = new ConcurrentLinkedQueue<>(); + protected final Set stopTracking = new HashSet<>(); + protected final Callback syncUpdateCallback = new Callback<>(runnables -> () -> runnables.forEach(Runnable::run)); + protected final Callback asyncUpdateCallback = new Callback<>(runnables -> () -> runnables.forEach(Runnable::run)); + protected Location location; + protected boolean baseGlowing; + + public DummyEntityData(Dummy dummy) { + this(dummy, new BasicCulling()); + } + + public DummyEntityData(Dummy 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 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 getPassengers() { + return List.of(); + } + + @Override + public Set getStartTracking() { + return ImmutableSet.copyOf(this.startTracking); + } + + @Override + public Map getMutableTracking() { + return this.asyncTracking; + } + + @Override + public Map getTracking() { + return this.trackingMap.snapshot(); + } + + @Override + public Set 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 getSyncUpdateCallback() { + return this.syncUpdateCallback; + } + + public Callback 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/data/IEntityData.java b/api/src/main/java/com/ticxo/modelengine/api/entity/data/IEntityData.java new file mode 100644 index 0000000..0fdf524 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/data/IEntityData.java @@ -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 CULL_TYPE_DATA_SAVER = (data, s, cullType) -> data.putString(s, cullType.name()); + SavedData.DataLoader 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 getPassengers(); + + default void markViewersDirty() { + } + + Set getStartTracking(); + + @Internal + Map getMutableTracking(); + + Map getTracking(); + + Set 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 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); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/entity/data/TrackingMap.java b/api/src/main/java/com/ticxo/modelengine/api/entity/data/TrackingMap.java new file mode 100644 index 0000000..79482d0 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/entity/data/TrackingMap.java @@ -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 { + private static final long serialVersionUID = 1L; + private final AtomicLong version = new AtomicLong(); + private transient volatile TrackingMap.Snapshot snapshot; + + public Map 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 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 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 function) { + CullType var3; + try { + var3 = super.compute(key, function); + } finally { + this.touch(); + } + + return var3; + } + + public CullType computeIfAbsent(UUID key, Function function) { + CullType var3; + try { + var3 = super.computeIfAbsent(key, function); + } finally { + this.touch(); + } + + return var3; + } + + public CullType computeIfPresent(UUID key, BiFunction function) { + CullType var3; + try { + var3 = super.computeIfPresent(key, function); + } finally { + this.touch(); + } + + return var3; + } + + public CullType merge(UUID key, CullType value, BiFunction function) { + CullType var4; + try { + var4 = super.merge(key, value, function); + } finally { + this.touch(); + } + + return var4; + } + + @Override + public void replaceAll(BiFunction function) { + try { + super.replaceAll(function); + } finally { + this.touch(); + } + } + + private static final class Snapshot { + private final long version; + private final Map map; + + private Snapshot(long version, Map map) { + this.version = version; + this.map = map; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/ErrorCollector.java b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorCollector.java new file mode 100644 index 0000000..f17c9b5 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorCollector.java @@ -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 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 getErrorList() { + return this.errorList; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/ErrorIncompatibleBone.java b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorIncompatibleBone.java new file mode 100644 index 0000000..30a1927 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorIncompatibleBone.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/ErrorMissingBoneBehaviorData.java b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorMissingBoneBehaviorData.java new file mode 100644 index 0000000..3788e4d --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorMissingBoneBehaviorData.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/ErrorNoFaceCube.java b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorNoFaceCube.java new file mode 100644 index 0000000..2a6800c --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorNoFaceCube.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/ErrorUnknownBoneBehavior.java b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorUnknownBoneBehavior.java new file mode 100644 index 0000000..f384447 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorUnknownBoneBehavior.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/ErrorUnknownFormat.java b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorUnknownFormat.java new file mode 100644 index 0000000..926c54b --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorUnknownFormat.java @@ -0,0 +1,8 @@ +package com.ticxo.modelengine.api.error; + +public class ErrorUnknownFormat extends IError.Error { + @Override + public String getErrorMessage() { + return "Error: Unknown format."; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/ErrorWrongBoneBehaviorDataType.java b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorWrongBoneBehaviorDataType.java new file mode 100644 index 0000000..cfd66ad --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/ErrorWrongBoneBehaviorDataType.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/IError.java b/api/src/main/java/com/ticxo/modelengine/api/error/IError.java new file mode 100644 index 0000000..3cb305e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/IError.java @@ -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; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadAngle.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadAngle.java new file mode 100644 index 0000000..2994f8d --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadAngle.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadEyeHeight.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadEyeHeight.java new file mode 100644 index 0000000..1128d66 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadEyeHeight.java @@ -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."; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadNamespace.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadNamespace.java new file mode 100644 index 0000000..6f1062e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadNamespace.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadTexture.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadTexture.java new file mode 100644 index 0000000..40070f3 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadTexture.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadTranslation.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadTranslation.java new file mode 100644 index 0000000..a93c3ea --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBadTranslation.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarnBoneTooLarge.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBoneTooLarge.java new file mode 100644 index 0000000..b2144ce --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBoneTooLarge.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarnBoxUV.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBoxUV.java new file mode 100644 index 0000000..a466436 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarnBoxUV.java @@ -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."; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarnDuplicateTexture.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarnDuplicateTexture.java new file mode 100644 index 0000000..a8ef418 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarnDuplicateTexture.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarnIncompatibleBoneBehavior.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarnIncompatibleBoneBehavior.java new file mode 100644 index 0000000..cd230ef --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarnIncompatibleBoneBehavior.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarnMultipleAngle.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarnMultipleAngle.java new file mode 100644 index 0000000..bccd7ce --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarnMultipleAngle.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarnNoHitbox.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarnNoHitbox.java new file mode 100644 index 0000000..89551aa --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarnNoHitbox.java @@ -0,0 +1,8 @@ +package com.ticxo.modelengine.api.error; + +public class WarnNoHitbox extends IError.Warn { + @Override + public String getErrorMessage() { + return "Warning: Missing hitbox."; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/error/WarningDuplicateBoneName.java b/api/src/main/java/com/ticxo/modelengine/api/error/WarningDuplicateBoneName.java new file mode 100644 index 0000000..3b14601 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/error/WarningDuplicateBoneName.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/AbstractEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/AbstractEvent.java new file mode 100644 index 0000000..a3f2d3d --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/AbstractEvent.java @@ -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()); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/AddModelEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/AddModelEvent.java new file mode 100644 index 0000000..f53d610 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/AddModelEvent.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/AnimationEndEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/AnimationEndEvent.java new file mode 100644 index 0000000..cd6d891 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/AnimationEndEvent.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/AnimationPlayEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/AnimationPlayEvent.java new file mode 100644 index 0000000..c2481a9 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/AnimationPlayEvent.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/BaseEntityInteractEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/BaseEntityInteractEvent.java new file mode 100644 index 0000000..f5593b4 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/BaseEntityInteractEvent.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/BoneTransformReadEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/BoneTransformReadEvent.java new file mode 100644 index 0000000..dc5ecdb --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/BoneTransformReadEvent.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/ModelDismountEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/ModelDismountEvent.java new file mode 100644 index 0000000..cca6fd1 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/ModelDismountEvent.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/ModelMountEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/ModelMountEvent.java new file mode 100644 index 0000000..34218e9 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/ModelMountEvent.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/ModelRegistrationEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/ModelRegistrationEvent.java new file mode 100644 index 0000000..928f389 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/ModelRegistrationEvent.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/ModelSetupEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/ModelSetupEvent.java new file mode 100644 index 0000000..0aa4721 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/ModelSetupEvent.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/RegisterBehaviorParserEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/RegisterBehaviorParserEvent.java new file mode 100644 index 0000000..d21e113 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/RegisterBehaviorParserEvent.java @@ -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 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 behaviorParsers) { + this.behaviorParsers = behaviorParsers; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/RegisterParserEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/RegisterParserEvent.java new file mode 100644 index 0000000..a055451 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/RegisterParserEvent.java @@ -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 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 parsers) { + this.parsers = parsers; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/events/RemoveModelEvent.java b/api/src/main/java/com/ticxo/modelengine/api/events/RemoveModelEvent.java new file mode 100644 index 0000000..956940f --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/events/RemoveModelEvent.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/BaseItemEnum.java b/api/src/main/java/com/ticxo/modelengine/api/generator/BaseItemEnum.java new file mode 100644 index 0000000..38bcb3a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/BaseItemEnum.java @@ -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 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 metaConsumer, Material material) { + this.metaConsumer = metaConsumer; + this.material = material; + } + + public Material getMaterial() { + return this.material; + } + + private static class Cons { + private static final BiConsumer MAP_CONSUMER = (meta, color) -> { + MapMeta map = (MapMeta)meta; + map.setColor(color); + }; + private static final BiConsumer LEATHER_CONSUMER = (meta, color) -> { + LeatherArmorMeta leather = (LeatherArmorMeta)meta; + leather.setColor(color); + }; + private static final BiConsumer POTION_CONSUMER = (meta, color) -> { + PotionMeta potion = (PotionMeta)meta; + potion.setColor(color); + }; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/ModelGenerator.java b/api/src/main/java/com/ticxo/modelengine/api/generator/ModelGenerator.java new file mode 100644 index 0000000..b144fe1 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/ModelGenerator.java @@ -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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/assets/BlueprintTexture.java b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/BlueprintTexture.java new file mode 100644 index 0000000..0d5cdb9 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/BlueprintTexture.java @@ -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 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 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) { + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/assets/ItemModel.java b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/ItemModel.java new file mode 100644 index 0000000..17698c1 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/ItemModel.java @@ -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 models = new ArrayList<>(); + + public Composite() { + super("minecraft:composite"); + } + + public List getModels() { + return this.models; + } + } + + public static class Model extends ItemModel { + protected final String model; + protected final List 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 getTints() { + return this.tints; + } + } + + public static class RangeDispatch extends ItemModel { + protected final List entries = new ArrayList<>(); + protected ItemModel fallback; + protected final String property = "minecraft:custom_model_data"; + + public RangeDispatch() { + super("minecraft:range_dispatch"); + } + + public List 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 cases = new ArrayList<>(); + protected ItemModel fallback; + protected final String property = "minecraft:custom_model_data"; + + public Select() { + super("minecraft:select"); + } + + public List 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) { + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/assets/ItemModelData.java b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/ItemModelData.java new file mode 100644 index 0000000..efe45f5 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/ItemModelData.java @@ -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 createItemStack() { + return this.createItemStack(ItemModelData.Context.builder().color(Color.WHITE).build()); + } + + public Set 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 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 getSubModels() { + return this.map.values(); + } + + public Set 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; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/assets/JavaDisplay.java b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/JavaDisplay.java new file mode 100644 index 0000000..4d43ec1 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/JavaDisplay.java @@ -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 sanitizer; + private final Predicate 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 sanitizer, Predicate isDirty) { + this.sanitizer = sanitizer; + this.isDirty = isDirty; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/assets/JavaItemModel.java b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/JavaItemModel.java new file mode 100644 index 0000000..0e4590a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/JavaItemModel.java @@ -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 textures = new HashMap<>(); + private final List elements = new ArrayList<>(); + private transient String name; + private transient float maxDistToOrigin = 0.0F; + private Map> 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 getTextures() { + return this.textures; + } + + public List getElements() { + return this.elements; + } + + public String getName() { + return this.name; + } + + public float getMaxDistToOrigin() { + return this.maxDistToOrigin; + } + + public Map> getDisplay() { + return this.display; + } + + public void setName(String name) { + this.name = name; + } + + public void setMaxDistToOrigin(float maxDistToOrigin) { + this.maxDistToOrigin = maxDistToOrigin; + } + + public void setDisplay(Map> 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 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 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; + } + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/assets/ModelAssets.java b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/ModelAssets.java new file mode 100644 index 0000000..ed431d7 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/ModelAssets.java @@ -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 textures = new ArrayList<>(); + private final Map> models = new HashMap<>(); + private String name; + + public List getTextures() { + return this.textures; + } + + public Map> getModels() { + return this.models; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/assets/TintSource.java b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/TintSource.java new file mode 100644 index 0000000..dd0a858 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/assets/TintSource.java @@ -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; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/blueprint/BlueprintBone.java b/api/src/main/java/com/ticxo/modelengine/api/generator/blueprint/BlueprintBone.java new file mode 100644 index 0000000..bec8256 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/blueprint/BlueprintBone.java @@ -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 children = new LinkedHashMap<>(); + private final Map> behaviors = new LinkedHashMap<>(); + private final transient Map, 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 getChildren() { + return this.children; + } + + public Map> getBehaviors() { + return this.behaviors; + } + + public Map, 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/blueprint/ModelBlueprint.java b/api/src/main/java/com/ticxo/modelengine/api/generator/blueprint/ModelBlueprint.java new file mode 100644 index 0000000..7ad6d73 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/blueprint/ModelBlueprint.java @@ -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 bones = new LinkedHashMap<>(); + private final Map animations = new LinkedHashMap<>(); + private final transient Set animationDescendingPriority = new LinkedHashSet<>(); + private final Map 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 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 tempMap = new LinkedHashMap<>(); + Set bones = new LinkedHashSet<>(this.bones.values()); + Set 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 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 boneEntry : this.flatMap.entrySet()) { + String name = boneEntry.getKey(); + BlueprintBone bone = boneEntry.getValue(); + + for (Entry> 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 getBones() { + return this.bones; + } + + public Map getAnimations() { + return this.animations; + } + + public Set getAnimationDescendingPriority() { + return this.animationDescendingPriority; + } + + public Map getAnimationsPlaceholders() { + return this.animationsPlaceholders; + } + + public String getName() { + return this.name; + } + + public Hitbox getMainHitbox() { + return this.mainHitbox; + } + + public float getShadowRadius() { + return this.shadowRadius; + } + + public Map 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; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/parser/ModelParser.java b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/ModelParser.java new file mode 100644 index 0000000..abf6cff --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/ModelParser.java @@ -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 generate(File var1, ErrorCollector var2) throws Exception; +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchBehaviorParser.java b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchBehaviorParser.java new file mode 100644 index 0000000..68dc80e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchBehaviorParser.java @@ -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); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchDeserializer.java b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchDeserializer.java new file mode 100644 index 0000000..dc53fe4 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchDeserializer.java @@ -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 { + 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); + }; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchModel.java b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchModel.java new file mode 100644 index 0000000..6a5b64e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/BlockbenchModel.java @@ -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 elements; + protected Map outliner; + protected Map textures; + protected Map animations; + protected final transient Map flatOutlinerByName = new HashMap<>(); + protected final transient Map flatOutlinerByUUID = new HashMap<>(); + protected String animation_variable_placeholders; + + public BlockbenchModel preprocess() { + LinkedList 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 elements, + Map outliner, + Map textures, + Map 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 getElements() { + return this.elements; + } + + public Map getOutliner() { + return this.outliner; + } + + public Map getTextures() { + return this.textures; + } + + public Map getAnimations() { + return this.animations; + } + + public Map getFlatOutlinerByName() { + return this.flatOutlinerByName; + } + + public Map 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 animators = new HashMap<>(); + protected Map 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 getAnimators() { + return this.animators; + } + + public Map getUnknown_animators() { + return this.unknown_animators; + } + } + + public static class Animator { + protected String name; + @Nullable + protected UUID uuid; + protected Boolean rotation_global; + protected Map> 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> 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 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 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 element = new HashSet<>(); + protected final Map 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 getElement() { + return this.element; + } + + public Map getChildGroup() { + return this.childGroup; + } + } + + public static class Keyframe { + protected String channel; + protected List> 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> 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 { + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/LegacyDeserializer.java b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/LegacyDeserializer.java new file mode 100644 index 0000000..b785759 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/LegacyDeserializer.java @@ -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 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 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 textures = new HashMap<>(); + HashMap 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 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 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 { + 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 { + 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 { + 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 { + 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 { + 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; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/v5_0_Deserializer.java b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/v5_0_Deserializer.java new file mode 100644 index 0000000..84d70a9 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/parser/blockbench/v5_0_Deserializer.java @@ -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 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 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 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 textures = new HashMap<>(); + HashMap 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 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 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 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 { + 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 { + 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)map, "x")); + this.flipBezierValues(keyframe, 0); + break; + case "ROTATION": + keyframe.getData_points().forEach(map -> { + this.tryFlipSign((Map)map, "x"); + this.tryFlipSign((Map)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 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 { + 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 { + 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 { + 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; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/skin/LimbData.java b/api/src/main/java/com/ticxo/modelengine/api/generator/skin/LimbData.java new file mode 100644 index 0000000..8e5ce8c --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/skin/LimbData.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.api.generator.skin; + +import com.destroystokyo.paper.profile.PlayerProfile; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; +import org.bukkit.profile.PlayerTextures; +import org.bukkit.profile.PlayerTextures.SkinModel; +import org.joml.Vector3f; + +public record LimbData(String limbType, Vector3f translation, Vector3f scale, boolean isHead) { + public ItemStack createItem(String url) { + ItemStack head = new ItemStack(Material.PLAYER_HEAD); + head.editMeta(itemMeta -> { + PlayerProfile profile = Bukkit.createProfile(UUID.randomUUID()); + + try { + PlayerTextures texture = profile.getTextures(); + texture.setSkin(new URL(url), SkinModel.CLASSIC); + profile.setTextures(texture); + } catch (MalformedURLException var4) { + throw new RuntimeException(var4); + } + + ((SkullMeta)itemMeta).setPlayerProfile(profile); + }); + return head; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/skin/SkinGeneratorService.java b/api/src/main/java/com/ticxo/modelengine/api/generator/skin/SkinGeneratorService.java new file mode 100644 index 0000000..d3753db --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/skin/SkinGeneratorService.java @@ -0,0 +1,11 @@ +package com.ticxo.modelengine.api.generator.skin; + +import java.util.concurrent.CompletableFuture; + +public interface SkinGeneratorService { + boolean isEnabled(); + + void onReload(); + + CompletableFuture generate(byte[] var1); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/generator/skin/SkinSplitter.java b/api/src/main/java/com/ticxo/modelengine/api/generator/skin/SkinSplitter.java new file mode 100644 index 0000000..0417cd7 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/generator/skin/SkinSplitter.java @@ -0,0 +1,19 @@ +package com.ticxo.modelengine.api.generator.skin; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +public interface SkinSplitter { + void reloadMapping(); + + LimbData getLimb(String var1, boolean var2); + + Map splitSkin(byte[] var1, boolean var2); + + default Map splitSkin(byte[] skinData, boolean slim, Collection limbTypes) { + HashMap map = new HashMap<>(this.splitSkin(skinData, slim)); + map.keySet().retainAll(limbTypes); + return map; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/interaction/DynamicHitbox.java b/api/src/main/java/com/ticxo/modelengine/api/interaction/DynamicHitbox.java new file mode 100644 index 0000000..154654c --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/interaction/DynamicHitbox.java @@ -0,0 +1,68 @@ +package com.ticxo.modelengine.api.interaction; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.UUID; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class DynamicHitbox { + private static final int pivotId = ModelEngineAPI.getEntityHandler().getNextEntityId(); + private static final UUID pivotUUID = UUID.randomUUID(); + private static final int hitboxId = ModelEngineAPI.getEntityHandler().getNextEntityId(); + private static final UUID hitboxUUID = UUID.randomUUID(); + private final Player player; + private final DataTracker positionTracker = new DataTracker<>(); + private int target; + + public DynamicHitbox(Player player, Vector position) { + this.player = player; + this.positionTracker.set(position); + ModelEngineAPI.getEntityHandler().spawnDynamicHitbox(this); + this.positionTracker.clearDirty(); + } + + public void update(Vector position) { + this.positionTracker.set(position.setY(position.getY())); + if (this.positionTracker.isDirty()) { + ModelEngineAPI.getEntityHandler().updateDynamicHitbox(this); + this.positionTracker.clearDirty(); + } + } + + public void destroy() { + ModelEngineAPI.getEntityHandler().destroyDynamicHitbox(this); + } + + public static int getPivotId() { + return pivotId; + } + + public static UUID getPivotUUID() { + return pivotUUID; + } + + public static int getHitboxId() { + return hitboxId; + } + + public static UUID getHitboxUUID() { + return hitboxUUID; + } + + public Player getPlayer() { + return this.player; + } + + public DataTracker getPositionTracker() { + return this.positionTracker; + } + + public int getTarget() { + return this.target; + } + + public void setTarget(int target) { + this.target = target; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/interaction/InteractionTracker.java b/api/src/main/java/com/ticxo/modelengine/api/interaction/InteractionTracker.java new file mode 100644 index 0000000..b676030 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/interaction/InteractionTracker.java @@ -0,0 +1,196 @@ +package com.ticxo.modelengine.api.interaction; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.callback.Callback; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; +import java.util.function.BiPredicate; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.util.RayTraceResult; +import org.bukkit.util.Vector; +import org.joml.Vector3f; + +public class InteractionTracker { + private final Map hitboxesUUID = Maps.newConcurrentMap(); + private final Map hitboxes = Maps.newConcurrentMap(); + private final Map playerRelay = Maps.newConcurrentMap(); + private final Map modelRelay = Maps.newConcurrentMap(); + private final Map entityRelay = Maps.newConcurrentMap(); + private final Callback> raytraceCallback = new Callback<>(predicates -> (player, cancel) -> { + for (BiPredicate predicate : predicates) { + cancel = predicate.test(player, cancel); + } + + return cancel; + }); + + public void raytraceHitboxes() { + this.hitboxes.values().removeIf(hitbox -> { + if (hitbox.isValid()) { + return false; + } else { + this.hitboxesUUID.remove(hitbox.getUniqueId()); + return true; + } + }); + if (this.hitboxes.isEmpty()) { + this.playerRelay.forEach((uuid, dynamicHitboxx) -> dynamicHitboxx.destroy()); + this.playerRelay.clear(); + } else { + for (Player player : Bukkit.getOnlinePlayers()) { + try { + if (!this.raytraceCallback.invoker().test(player, false)) { + if (player.getGameMode() == GameMode.SPECTATOR) { + this.playerRelay.computeIfPresent(player.getUniqueId(), (uuid, dynamicHitboxx) -> { + dynamicHitboxx.destroy(); + return null; + }); + } else { + Vector startVec = player.getEyeLocation().toVector(); + Vector dirVec = player.getEyeLocation().getDirection(); + if (Double.isFinite(startVec.getX()) + && Double.isFinite(startVec.getY()) + && Double.isFinite(startVec.getZ()) + && Double.isFinite(dirVec.getX()) + && Double.isFinite(dirVec.getY()) + && Double.isFinite(dirVec.getZ())) { + Vector3f start = startVec.toVector3f(); + Vector3f dir = dirVec.toVector3f(); + double traceDist = player.getGameMode() == GameMode.CREATIVE ? 5.0 : 3.0; + double dist = Double.MAX_VALUE; + HitboxEntity closestHitbox = null; + RayTraceResult closestResult = null; + Iterator hitPos = this.hitboxes.values().iterator(); + + while (true) { + if (hitPos.hasNext()) { + HitboxEntity hitbox = (HitboxEntity)hitPos.next(); + OrientedBoundingBox obb = hitbox.getOrientedBoundingBox(); + if (obb == null + || !obb.isWithinRange(start, traceDist) + || hitbox.getLocation().getWorld() != player.getWorld() + || this.entityRelay.getOrDefault(hitbox.getEntityId(), player.getEntityId() + 1) == player.getEntityId()) { + continue; + } + + ActiveModel hitModel = hitbox.getBone().getActiveModel(); + if (hitModel == null + || hitModel.getModeledEntity() == null + || hitModel.getModeledEntity().getBase().getEntityId() == player.getEntityId()) { + continue; + } + + if (!obb.contains(start)) { + RayTraceResult result = obb.rayTrace(start, dir, traceDist, null); + if (result != null) { + double hitDistSqr = result.getHitPosition().distanceSquared(startVec); + if (!(dist < hitDistSqr)) { + closestHitbox = hitbox; + closestResult = result; + } + } + continue; + } + + closestHitbox = hitbox; + closestResult = null; + } + + if (closestHitbox == null) { + this.playerRelay.computeIfPresent(player.getUniqueId(), (uuid, dynamicHitboxx) -> { + dynamicHitboxx.destroy(); + return null; + }); + } else { + Vector hitPosx = closestResult == null ? startVec.add(dirVec.multiply(traceDist)) : closestResult.getHitPosition(); + DynamicHitbox dynamicHitbox = this.playerRelay.computeIfAbsent(player.getUniqueId(), uuid -> new DynamicHitbox(player, hitPosx)); + dynamicHitbox.setTarget(closestHitbox.getEntityId()); + dynamicHitbox.update(hitPosx); + } + break; + } + } else { + this.playerRelay.computeIfPresent(player.getUniqueId(), (uuid, dynamicHitboxx) -> { + dynamicHitboxx.destroy(); + return null; + }); + } + } + } + } catch (Throwable var20) { + var20.printStackTrace(); + } + } + } + } + + public void addHitbox(HitboxEntity hitbox) { + this.hitboxesUUID.put(hitbox.getUniqueId(), hitbox.getEntityId()); + this.hitboxes.put(hitbox.getEntityId(), hitbox); + } + + public void removeHitbox(UUID uuid) { + Integer id = this.hitboxesUUID.remove(uuid); + if (id != null) { + this.hitboxes.remove(id); + } + } + + public void removeHitbox(int id) { + HitboxEntity hitbox = this.hitboxes.remove(id); + if (hitbox != null) { + this.hitboxesUUID.remove(hitbox.getUniqueId()); + } + } + + public HitboxEntity getHitbox(UUID uuid) { + Integer id = this.hitboxesUUID.get(uuid); + return id == null ? null : this.hitboxes.get(id); + } + + public HitboxEntity getHitbox(int id) { + return this.hitboxes.get(id); + } + + public void removeDynamicHitbox(UUID uuid) { + this.playerRelay.remove(uuid); + } + + public DynamicHitbox getDynamicHitbox(UUID uuid) { + return this.playerRelay.get(uuid); + } + + public void setModelRelay(int id, ActiveModel activeModel) { + this.modelRelay.put(id, activeModel); + } + + public void removeModelRelay(int id) { + ActiveModel activeModel = this.modelRelay.remove(id); + } + + public ActiveModel getModelRelay(int id) { + return this.modelRelay.get(id); + } + + public void setEntityRelay(int id, Integer hitboxId) { + this.entityRelay.put(id, hitboxId); + } + + public void removeEntityRelay(int id) { + this.entityRelay.remove(id); + } + + public Integer getEntityRelay(int id) { + return this.entityRelay.get(id); + } + + public Callback> getRaytraceCallback() { + return this.raytraceCallback; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/lod/AnimationLODHandler.java b/api/src/main/java/com/ticxo/modelengine/api/lod/AnimationLODHandler.java new file mode 100644 index 0000000..fcfb850 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/lod/AnimationLODHandler.java @@ -0,0 +1,220 @@ +package com.ticxo.modelengine.api.lod; + +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.utils.callback.Callback; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.math.Box; +import com.ticxo.modelengine.api.utils.math.TMath; +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.util.BoundingBox; + +public class AnimationLODHandler { + private static final Set ACTIVE = new ObjectOpenHashSet(); + private static final Callback> TOGGLE_CALLBACK = new Callback<>( + consumers -> flag -> consumers.forEach(booleanConsumer -> booleanConsumer.accept(flag)) + ); + private static final Callback> PLAYER_CALLBACK = new Callback<>( + biConsumers -> (uuid, flag) -> biConsumers.forEach(uuidBooleanBiConsumer -> uuidBooleanBiConsumer.accept(uuid, flag)) + ); + private static boolean ENABLED; + private static boolean DEFAULT; + private static double FALLOFF_LENGTH; + private static double FALLOFF_MULTIPLIER; + private static double IGNORE_DISTANCE; + private static double IGNORE_DISTANCE_SQR; + private static double IGNORE_MULTIPLIER; + private static double MAX_RATE_MULTIPLIER; + private static double MIN_RATE_MULTIPLIER; + private final ModeledEntity modeledEntity; + private final UUID toggleCallback; + private final UUID playerCallback; + private final Object2ObjectMap trackers = new Object2ObjectOpenHashMap(); + private final AnimationLODHandler.LODTracker fullUpdate; + private Boolean enabled; + + public static void updateConfig() { + ENABLED = ConfigProperty.ANIMATION_LOD_ENABLED.getBoolean(); + DEFAULT = ConfigProperty.ANIMATION_LOD_DEFAULT.getBoolean(); + FALLOFF_LENGTH = ConfigProperty.ANIMATION_LOD_FALLOFF_LENGTH.getDouble(); + FALLOFF_MULTIPLIER = ConfigProperty.ANIMATION_LOD_FALLOFF_MULTIPLIER.getDouble(); + IGNORE_DISTANCE = ConfigProperty.ANIMATION_LOD_IGNORE_DISTANCE.getDouble(); + IGNORE_DISTANCE_SQR = IGNORE_DISTANCE * IGNORE_DISTANCE; + IGNORE_MULTIPLIER = ConfigProperty.ANIMATION_LOD_IGNORE_MULTIPLIER.getDouble(); + MAX_RATE_MULTIPLIER = ConfigProperty.ANIMATION_LOD_MAX_RATE_MULTIPLIER.getDouble(); + MIN_RATE_MULTIPLIER = ConfigProperty.ANIMATION_LOD_MIN_RATE_MULTIPLIER.getDouble(); + } + + public static void setGlobalEnabled(boolean flag) { + if (ENABLED != flag) { + ENABLED = flag; + TOGGLE_CALLBACK.invoker().accept(flag); + } + } + + public static boolean isGlobalEnabled() { + return ENABLED; + } + + public static void registerPlayer(UUID uuid) { + setPlayerActive(uuid, DEFAULT); + } + + public static void setPlayerActive(UUID uuid, boolean flag) { + if (flag && !ACTIVE.contains(uuid)) { + ACTIVE.add(uuid); + PLAYER_CALLBACK.invoker().accept(uuid, true); + } else if (!flag) { + ACTIVE.remove(uuid); + PLAYER_CALLBACK.invoker().accept(uuid, false); + } + } + + public AnimationLODHandler(ModeledEntity modeledEntity) { + this.modeledEntity = modeledEntity; + this.fullUpdate = new AnimationLODHandler.LODTracker(UUID.randomUUID(), modeledEntity); + this.fullUpdate.canSkip = false; + this.toggleCallback = TOGGLE_CALLBACK.subscribe(flag -> { + if (!flag) { + this.trackers.clear(); + } + }); + this.playerCallback = PLAYER_CALLBACK.subscribe(this::updatePlayer); + } + + public AnimationLODHandler.LODTracker tick(UUID uuid) { + if (this.enabled() && ACTIVE.contains(uuid)) { + AnimationLODHandler.LODTracker tracker = (AnimationLODHandler.LODTracker)this.trackers + .computeIfAbsent(uuid, uuid1 -> new AnimationLODHandler.LODTracker(uuid, this.modeledEntity)); + if (tracker.tick(ServerInfo.CURRENT_TICK)) { + this.trackers.remove(uuid); + tracker.canSkip = true; + } + + return tracker; + } else { + return this.fullUpdate; + } + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + if (!this.enabled()) { + this.trackers.clear(); + } + } + + public boolean enabled() { + return this.enabled == null ? ENABLED : this.enabled; + } + + public void destroy() { + TOGGLE_CALLBACK.unsubscribe(this.toggleCallback); + PLAYER_CALLBACK.unsubscribe(this.playerCallback); + } + + private void updatePlayer(UUID uuid, boolean flag) { + if (flag) { + this.trackers.computeIfAbsent(uuid, uuid1 -> new AnimationLODHandler.LODTracker(uuid, this.modeledEntity)); + } else { + this.trackers.remove(uuid); + } + } + + public Boolean getEnabled() { + return this.enabled; + } + + public class LODTracker { + private final UUID uuid; + private final ModeledEntity modeledEntity; + private int lastCheckedTick = ServerInfo.CURRENT_TICK; + private final DataTracker tickDuration = new DataTracker<>(1); + private double distanceSqr = -1.0; + private double tickRate = 1.0; + private double cumulatedTick = 0.0; + private int lastSuccessfulTick = 0; + private boolean canSkip; + + public boolean tick(int tick) { + if (this.canRemoveSelf()) { + this.canSkip = true; + return true; + } else if (this.lastCheckedTick == tick) { + return false; + } else { + this.lastCheckedTick = tick; + this.calculateTickRate(); + this.cumulatedTick = this.cumulatedTick + this.tickRate; + int floorTick = TMath.floor(this.cumulatedTick); + this.canSkip = this.lastSuccessfulTick == floorTick; + this.lastSuccessfulTick = floorTick; + if (!this.canSkip) { + this.tickDuration.clearDirty(); + this.tickDuration.set(Math.max(TMath.ceil((Math.ceil(this.cumulatedTick) - this.cumulatedTick) / this.tickRate), 1)); + } + + return false; + } + } + + public boolean canRemoveSelf() { + return !AnimationLODHandler.this.enabled() || !AnimationLODHandler.ACTIVE.contains(this.uuid) || Bukkit.getPlayer(this.uuid) == null; + } + + public void calculateTickRate() { + if (AnimationLODHandler.this.enabled() && AnimationLODHandler.ACTIVE.contains(this.uuid)) { + Player player = Bukkit.getPlayer(this.uuid); + if (player != null) { + BaseEntity base = this.modeledEntity.getBase(); + Location loc = base.getLocation(); + if (loc.getWorld() == player.getWorld()) { + double dSqr = loc.distanceSquared(player.getLocation()); + if (!TMath.isSimilar(dSqr, this.distanceSqr)) { + this.distanceSqr = dSqr; + if (AnimationLODHandler.IGNORE_DISTANCE_SQR >= dSqr) { + this.tickRate = 1.0; + } else { + Box cullBox = base.getData().getCullHitbox(); + BoundingBox box = cullBox == null ? base.getBoundingBox() : cullBox.createBoundingBox(loc.toVector()); + double ignoreMul = (box.getWidthX() + box.getHeight() + box.getWidthZ()) / 3.0 * AnimationLODHandler.IGNORE_MULTIPLIER; + float distance = (float)Math.max(0.0, Math.sqrt(dSqr) - AnimationLODHandler.IGNORE_DISTANCE * ignoreMul); + if (TMath.isSimilar(distance, 0.0F)) { + this.tickRate = 1.0; + } else { + this.tickRate = Math.pow(AnimationLODHandler.FALLOFF_MULTIPLIER, distance / AnimationLODHandler.FALLOFF_LENGTH); + } + } + + this.tickRate = TMath.clamp(this.tickRate, AnimationLODHandler.MIN_RATE_MULTIPLIER, AnimationLODHandler.MAX_RATE_MULTIPLIER); + } + } + } + } + } + + public LODTracker(UUID uuid, ModeledEntity modeledEntity) { + this.uuid = uuid; + this.modeledEntity = modeledEntity; + } + + public DataTracker getTickDuration() { + return this.tickDuration; + } + + public boolean isCanSkip() { + return this.canSkip; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/lod/BoneSnapshotHandler.java b/api/src/main/java/com/ticxo/modelengine/api/lod/BoneSnapshotHandler.java new file mode 100644 index 0000000..e6ed39d --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/lod/BoneSnapshotHandler.java @@ -0,0 +1,52 @@ +package com.ticxo.modelengine.api.lod; + +import com.ticxo.modelengine.api.model.render.DisplayBone; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +public class BoneSnapshotHandler { + private final DisplayBone bone; + private final Map snapshots = new ConcurrentHashMap<>(); + private BoneSnapshotHandler.Snapshot snapshot; + + public void recordSnapshot() { + int pos = this.bone.getPosition().get().hashCode(); + int lRot = this.bone.getLeftRotation().get().hashCode(); + int scl = this.bone.getScale().get().hashCode(); + int rRot = this.bone.getRightRotation().get().hashCode(); + BoneSnapshotHandler.Snapshot prev = this.snapshot; + if (prev == null || prev.position != pos || prev.leftRotation != lRot || prev.scale != scl || prev.rightRotation != rRot) { + this.snapshot = new BoneSnapshotHandler.Snapshot(pos, lRot, scl, rRot); + } + } + + public byte getUpdate(UUID uuid) { + BoneSnapshotHandler.Snapshot lastSnapshot = this.snapshots.get(uuid); + if (lastSnapshot == this.snapshot) { + return 0; + } else { + this.snapshots.put(uuid, this.snapshot); + return lastSnapshot == null ? 15 : lastSnapshot.compare(this.snapshot); + } + } + + public void remove(UUID uuid) { + this.snapshots.remove(uuid); + } + + public BoneSnapshotHandler(DisplayBone bone) { + this.bone = bone; + } + + public record Snapshot(int position, int leftRotation, int scale, int rightRotation) { + public byte compare(BoneSnapshotHandler.Snapshot snapshot) { + return (byte)( + (this.position != snapshot.position ? 1 : 0) + | (this.leftRotation != snapshot.leftRotation ? 2 : 0) + | (this.scale != snapshot.scale ? 4 : 0) + | (this.rightRotation != snapshot.rightRotation ? 8 : 0) + ); + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/menu/AbstractScreen.java b/api/src/main/java/com/ticxo/modelengine/api/menu/AbstractScreen.java new file mode 100644 index 0000000..2ce2e90 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/menu/AbstractScreen.java @@ -0,0 +1,121 @@ +package com.ticxo.modelengine.api.menu; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +public abstract class AbstractScreen { + protected final Player viewer; + protected final Inventory inventory; + protected final List widgets = new ArrayList<>(); + protected final Map widgetReference = new HashMap<>(); + protected final Set dirtySlots = new HashSet<>(); + + public AbstractScreen(Player viewer, String title, int rows) { + this(viewer, Component.text(title), rows); + } + + public AbstractScreen(Player viewer, Component component, int rows) { + this.viewer = viewer; + this.inventory = Bukkit.createInventory(null, rows * 9, component); + } + + public void openScreen() { + this.draw(true); + this.viewer.openInventory(this.inventory); + ModelEngineAPI.getAPI().getScreenManager().registerScreen(this); + } + + public void onTick() { + if (!this.dirtySlots.isEmpty()) { + this.draw(false); + } + } + + public void onClick(Player player, int slot, InventoryClickEvent event) { + Widget widget = this.widgetReference.get(slot); + if (widget != null) { + widget.onClick(this, player, slot, event); + } + } + + public void onClickPlayer(Player player, int slot, InventoryClickEvent event) { + if (event.isShiftClick()) { + event.setCancelled(true); + } + } + + public void addWidget(Widget widget) { + this.widgets.add(widget); + } + + public void markSlotDirty(int slot) { + this.dirtySlots.add(slot); + } + + public void markSlotsDirty(int... slots) { + for (int slot : slots) { + this.dirtySlots.add(slot); + } + } + + public void draw(boolean all) { + int size = this.inventory.getSize(); + if (all) { + this.inventory.clear(); + this.widgetReference.clear(); + + for (int i = 0; i < size; i++) { + for (int j = this.widgets.size() - 1; j >= 0; j--) { + Widget widget = this.widgets.get(j); + ItemStack item = widget.getItemForSlot(size, i); + if (item != null) { + this.inventory.setItem(i, item); + this.widgetReference.put(i, widget); + break; + } + } + } + } else { + if (this.dirtySlots.isEmpty()) { + return; + } + + label40: + for (int slot : this.dirtySlots) { + for (int jx = this.widgets.size() - 1; jx >= 0; jx--) { + Widget widget = this.widgets.get(jx); + ItemStack item = widget.getItemForSlot(size, slot); + if (item != null) { + this.inventory.setItem(slot, item); + this.widgetReference.put(slot, widget); + continue label40; + } + } + + this.inventory.setItem(slot, null); + this.widgetReference.remove(slot); + } + + this.dirtySlots.clear(); + } + } + + public Player getViewer() { + return this.viewer; + } + + public Inventory getInventory() { + return this.inventory; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/menu/ScreenManager.java b/api/src/main/java/com/ticxo/modelengine/api/menu/ScreenManager.java new file mode 100644 index 0000000..557ab8b --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/menu/ScreenManager.java @@ -0,0 +1,39 @@ +package com.ticxo.modelengine.api.menu; + +import com.google.common.collect.Maps; +import java.util.Map; +import org.bukkit.inventory.Inventory; + +public class ScreenManager { + private final Map screens = Maps.newConcurrentMap(); + + public void registerScreen(AbstractScreen screen) { + this.screens.put(screen.inventory, screen); + } + + public void unregisterScreen(Inventory inventory) { + this.screens.remove(inventory); + } + + public void unregisterScreen(AbstractScreen screen) { + this.screens.remove(screen.inventory); + } + + public AbstractScreen getScreen(Inventory inventory) { + return this.screens.get(inventory); + } + + public boolean isScreen(Inventory inventory) { + return this.screens.containsKey(inventory); + } + + public void updateAllScreens() { + for (AbstractScreen screen : this.screens.values()) { + screen.onTick(); + } + } + + public Map getScreens() { + return this.screens; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/menu/Widget.java b/api/src/main/java/com/ticxo/modelengine/api/menu/Widget.java new file mode 100644 index 0000000..db11f7f --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/menu/Widget.java @@ -0,0 +1,15 @@ +package com.ticxo.modelengine.api.menu; + +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public interface Widget { + static int toSlot(int x, int y) { + return y * 9 + x; + } + + ItemStack getItemForSlot(int var1, int var2); + + void onClick(AbstractScreen var1, Player var2, int var3, InventoryClickEvent var4); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/ActiveModel.java b/api/src/main/java/com/ticxo/modelengine/api/model/ActiveModel.java new file mode 100644 index 0000000..bf59e2d --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/ActiveModel.java @@ -0,0 +1,213 @@ +package com.ticxo.modelengine.api.model; + +import com.ticxo.modelengine.api.animation.handler.AnimationHandler; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.LeashManager; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.type.Leash; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.utils.callback.Callback; +import com.ticxo.modelengine.api.utils.data.io.DataIO; +import com.ticxo.modelengine.api.utils.meta.IMetaHolder; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import org.bukkit.Color; +import org.bukkit.entity.Display.Billboard; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3fc; + +public interface ActiveModel extends DataIO, IMetaHolder { + ModeledEntity getModeledEntity(); + + void setModeledEntity(ModeledEntity var1); + + ModelBlueprint getBlueprint(); + + ModelRenderer getModelRenderer(); + + AnimationHandler getAnimationHandler(); + + Optional getPivotOverride(); + + void setPivotOverride(PivotOverride var1); + + Map getBones(); + + Map, BehaviorManager> getBehaviorManagers(); + + Map, BehaviorRenderer> getBehaviorRenderers(); + + boolean isMainHitbox(); + + void setMainHitbox(boolean var1); + + Vector3fc getScale(); + + void setScale(double var1); + + void setScale(Vector3fc var1); + + Vector3fc getHitboxScale(); + + void setHitboxScale(double var1); + + void setHitboxScale(Vector3fc var1); + + void tick(); + + void destroy(); + + boolean isDestroyed(); + + boolean isRemoved(); + + void setRemoved(boolean var1); + + void setAutoRendererInitialization(boolean var1); + + boolean isHitboxVisible(); + + void setHitboxVisible(boolean var1); + + boolean isShadowVisible(); + + void setShadowVisible(boolean var1); + + float getViewRange(); + + void setViewRange(float var1); + + void initializeRenderer(); + + void generateModel(); + + void forceGenerateBone(String var1, String var2, BlueprintBone var3); + + void removeBone(String var1); + + Callback getScaleCallback(); + + Callback getPreSendCallback(); + + Callback getPostSendCallback(); + + void setCanHurt(boolean var1); + + boolean canHurt(); + + Color getDefaultTint(); + + void setDefaultTint(Color var1); + + Color getDamageTint(); + + void setDamageTint(Color var1); + + boolean wasMarkedHurt(); + + boolean isMarkedHurt(); + + boolean isGlowing(); + + void setGlowing(@Nullable Boolean var1); + + int getGlowColor(); + + void setGlowColor(@Nullable Integer var1); + + @Nullable + Set getGlowAudience(); + + void setGlowAudience(@Nullable Set var1); + + int getBlockLight(); + + void setBlockLight(int var1); + + int getSkyLight(); + + void setSkyLight(int var1); + + Billboard getBillboard(); + + void setBillboard(Billboard var1); + + boolean isOnFire(); + + void setOnFire(Boolean var1); + + boolean canRenderFire(); + + void setRenderFire(Boolean var1); + + float getXHeadRot(); + + float getYHeadRot(); + + float getYBodyRot(); + + boolean isLockPitch(); + + void setLockPitch(boolean var1); + + boolean isLockYaw(); + + void setLockYaw(boolean var1); + + void setLockedYHeadRot(float var1); + + float getLockedYHeadRot(); + + void setLockedXHeadRot(float var1); + + float getLockedXHeadRot(); + + void setLockedYBodyRot(float var1); + + float getLockedYBodyRot(); + + boolean isModelRotationLocked(); + + void setModelRotationLocked(Boolean var1); + + boolean isInvisUpdate(); + + void setInvisUpdate(boolean var1); + + boolean isCameraPivot(); + + void setCameraPivot(boolean var1); + + default Optional getBone(String boneId) { + return Optional.ofNullable(this.getBones().get(boneId)); + } + + Optional> getBehaviorManager(BoneBehaviorType var1); + + Optional getBehaviorRenderer(BoneBehaviorType var1); + + default > Optional getMountManager() { + Optional maybe = this.getBehaviorManager(BoneBehaviorTypes.MOUNT); + return maybe.map(behaviorManager -> (T)behaviorManager); + } + + default > Optional getLeashManager() { + Optional maybe = this.getBehaviorManager(BoneBehaviorTypes.LEASH); + return maybe.map(behaviorManager -> (T)behaviorManager); + } + + @FunctionalInterface + public interface Scale { + void onScale(ActiveModel var1, double var2); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/ModelRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/model/ModelRegistry.java new file mode 100644 index 0000000..8f791f7 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/ModelRegistry.java @@ -0,0 +1,25 @@ +package com.ticxo.modelengine.api.model; + +import com.google.common.collect.Ordering; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.utils.registry.TUnaryRegistry; +import java.util.Collection; +import java.util.PriorityQueue; + +public class ModelRegistry extends TUnaryRegistry { + private final PriorityQueue orderedId = new PriorityQueue<>(Ordering.natural()); + + public void registerBlueprint(ModelBlueprint blueprint) { + this.orderedId.add(blueprint.getName()); + this.register(blueprint.getName(), blueprint); + } + + public void clearRegistry() { + this.orderedId.clear(); + this.registry.clear(); + } + + public Collection getOrderedId() { + return this.orderedId; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/ModelUpdaters.java b/api/src/main/java/com/ticxo/modelengine/api/model/ModelUpdaters.java new file mode 100644 index 0000000..b44b25f --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/ModelUpdaters.java @@ -0,0 +1,283 @@ +package com.ticxo.modelengine.api.model; + +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.utils.Profiler; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import com.ticxo.modelengine.api.utils.ticker.DualTicker; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Consumer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.persistence.PersistentDataType; + +public class ModelUpdaters { + private final ExecutorService executors = Executors.newWorkStealingPool( + ConfigProperty.MAX_ENGINE_THREADS.getIntOrIfNeg(() -> Runtime.getRuntime().availableProcessors()) + ); + private final Map uuidLookup = Maps.newConcurrentMap(); + private final Map idLookup = Maps.newConcurrentMap(); + private final RenderParsers parsers; + private final NetworkHandler networkHandler; + private final NMSHandler nmsHandler; + private final Set desyncMonitored = Sets.newConcurrentHashSet(); + private final AtomicBoolean ticking = new AtomicBoolean(false); + private final AtomicLong removalEpoch = new AtomicLong(); + private final AtomicLong membershipEpoch = new AtomicLong(); + private static final ModeledEntity[] EMPTY_SNAPSHOT = new ModeledEntity[0]; + private ModeledEntity[] tickSnapshot = EMPTY_SNAPSHOT; + private long tickSnapshotEpoch = -1L; + private final Profiler profiler = new Profiler(200); + private volatile boolean bundleEverything; + private volatile boolean batching; + + public ModelUpdaters() { + this.parsers = ModelEngineAPI.getNMSHandler().createParsers(); + this.networkHandler = ModelEngineAPI.getNetworkHandler(); + this.nmsHandler = ModelEngineAPI.getNMSHandler(); + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> this.bundleEverything = ConfigProperty.BUNDLE_EVERYTHING.getBoolean()); + } + + public void start() { + DualTicker.queueRepeatingSyncTask(this::tick, 0, 0); + } + + public void tick() { + if (this.ticking.compareAndSet(false, true)) { + this.profiler.startProfiling(); + long epoch = this.membershipEpoch.get(); + if (epoch != this.tickSnapshotEpoch) { + this.tickSnapshot = this.uuidLookup.values().toArray(EMPTY_SNAPSHOT); + this.tickSnapshotEpoch = epoch; + } + + ModeledEntity[] snapshot = this.tickSnapshot; + if (snapshot.length == 0) { + this.profiler.stopProfiling(); + this.ticking.set(false); + } else { + this.batching = this.bundleEverything; + if (this.batching) { + this.networkHandler.startBatch(); + } + + AtomicInteger remaining = new AtomicInteger(1); + + try { + for (ModeledEntity entity : snapshot) { + BaseEntity base = entity.getBase(); + remaining.incrementAndGet(); + + try { + this.executors.execute(() -> { + try { + entity.runTickTasks(ModeledEntity.Phase.PRE_DATA_SYNC); + base.getData().asyncUpdate(); + entity.runTickTasks(ModeledEntity.Phase.PRE_MODEL_TICK); + if (!entity.tick()) { + this.forceRemoveModeledEntity(entity); + } else { + entity.runTickTasks(ModeledEntity.Phase.PRE_MODEL_RENDER); + this.forRenderers(entity, modelRenderer -> modelRenderer.sendToClient(this.parsers)); + entity.runTickTasks(ModeledEntity.Phase.POST_MODEL_RENDER); + if (entity.shouldBeSaved() && entity.getTick() % 200 == 0) { + entity.updateSaveCache(); + } + } + } catch (Throwable var8x) { + var8x.printStackTrace(); + } finally { + if (remaining.decrementAndGet() == 0) { + this.finishTick(); + } + } + }); + } catch (Throwable var16) { + var16.printStackTrace(); + remaining.decrementAndGet(); + } + } + } catch (Throwable var18) { + var18.printStackTrace(); + } finally { + if (remaining.decrementAndGet() == 0) { + this.finishTick(); + } + } + } + + try { + for (UUID uuid : this.desyncMonitored) { + this.networkHandler.ping(uuid); + } + } catch (Throwable var17) { + var17.printStackTrace(); + } + } + } + + private void finishTick() { + try { + this.nmsHandler.sendPivotOverrides(); + } catch (Throwable var10) { + var10.printStackTrace(); + } finally { + if (this.batching) { + this.batching = false; + + try { + this.networkHandler.endBatch(); + } catch (Throwable var9) { + var9.printStackTrace(); + } + } + + this.profiler.stopProfiling(); + this.ticking.set(false); + } + } + + public void startDesyncMonitor(UUID uuid) { + this.desyncMonitored.add(uuid); + } + + public void stopDesyncMonitor(UUID uuid) { + this.desyncMonitored.remove(uuid); + } + + private void forRenderers(ModeledEntity modeledEntity, Consumer rendererConsumer) { + IEntityData data = modeledEntity.getBase().getData(); + Map models = modeledEntity.getModels(); + if (!models.isEmpty()) { + for (ActiveModel model : models.values()) { + if (!model.getModelRenderer().isInitialized()) { + return; + } + } + + for (ActiveModel modelx : models.values()) { + rendererConsumer.accept(modelx.getModelRenderer()); + } + + data.cleanup(); + } + } + + public void end() { + this.executors.shutdown(); + + try { + if (!this.executors.awaitTermination(10L, TimeUnit.SECONDS)) { + this.executors.shutdownNow(); + } + } catch (InterruptedException var2) { + this.executors.shutdownNow(); + } + } + + public Optional registerModeledEntity(BaseEntity base, ModeledEntity modeledEntity) { + this.idLookup.put(base.getEntityId(), modeledEntity); + ModeledEntity previous = this.uuidLookup.put(base.getUUID(), modeledEntity); + this.membershipEpoch.incrementAndGet(); + return Optional.ofNullable(previous); + } + + public ModeledEntity getModeledEntity(int id) { + return this.idLookup.get(id); + } + + public void rekeyEntityId(UUID uuid, int oldId, int newId) { + if (oldId != newId) { + ModeledEntity model = this.uuidLookup.get(uuid); + if (model != null) { + this.idLookup.remove(oldId, model); + this.idLookup.put(newId, model); + } + } + } + + public ModeledEntity getModeledEntity(UUID uuid) { + return uuid == null ? null : this.uuidLookup.get(uuid); + } + + public ModeledEntity removeModeledEntity(int id) { + ModeledEntity model = this.idLookup.get(id); + if (model != null) { + model.markRemoved(); + } + + return model; + } + + public ModeledEntity removeModeledEntity(UUID uuid) { + if (uuid == null) { + return null; + } else { + ModeledEntity model = this.uuidLookup.get(uuid); + if (model != null) { + model.markRemoved(); + } + + return model; + } + } + + public long getRemovalEpoch() { + return this.removalEpoch.get(); + } + + public void forceRemoveModeledEntity(ModeledEntity model) { + boolean registered = this.uuidLookup.remove(model.getBase().getUUID(), model); + this.idLookup.remove(model.getBase().getEntityId(), model); + this.removalEpoch.incrementAndGet(); + this.membershipEpoch.incrementAndGet(); + model.getBase().setForcedAlive(false); + if (registered + && model.getBase().getOriginal() instanceof Entity entity + && !(entity instanceof Player) + && (model.getBase().isRemoved() || !model.getBase().isAlive())) { + ModelEngineAPI.getEntityHandler().clearForcedInvisible(entity.getUniqueId()); + } + + if (ServerInfo.IS_FOLIA) { + DualTicker.queueSyncTask(model::destroy); + } else { + model.destroy(); + } + } + + public void saveAllModels() { + for (ModeledEntity model : this.uuidLookup.values()) { + if (model.shouldBeSaved() && model.getBase().getOriginal() instanceof Entity entity && !(entity instanceof Player)) { + String cachedJson = model.getCachedSaveJson(); + if (cachedJson != null) { + entity.getPersistentDataContainer().set(SavedData.DATA_KEY, PersistentDataType.STRING, cachedJson); + } else { + model.save().ifPresent(data -> entity.getPersistentDataContainer().set(SavedData.DATA_KEY, PersistentDataType.STRING, data.toString())); + } + } + } + } + + public Profiler getProfiler() { + return this.profiler; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/ModeledEntity.java b/api/src/main/java/com/ticxo/modelengine/api/model/ModeledEntity.java new file mode 100644 index 0000000..61f8e46 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/ModeledEntity.java @@ -0,0 +1,132 @@ +package com.ticxo.modelengine.api.model; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionHandler; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.utils.callback.Callback; +import com.ticxo.modelengine.api.utils.data.io.DataIO; +import com.ticxo.modelengine.api.utils.meta.IMetaHolder; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface ModeledEntity extends DataIO, IMetaHolder { + BaseEntity getBase(); + + AnimationLODHandler getAnimationLodHandler(); + + int getTick(); + + boolean tick(); + + void destroy(); + + boolean isInitialized(); + + boolean isDestroyed(); + + void markRemoved(); + + void restore(); + + void queuePostInitTask(Runnable var1); + + boolean isBaseEntityVisible(); + + void setBaseEntityVisible(boolean var1); + + void markHurt(); + + int getHurtTick(); + + boolean shouldBeSaved(); + + void setSaved(boolean var1); + + @Nullable + String getCachedSaveJson(); + + void updateSaveCache(); + + boolean isModelRotationLocked(); + + void setModelRotationLocked(boolean var1); + + boolean isGlowing(); + + int getGlowColor(); + + float getYHeadRot(); + + float getXHeadRot(); + + float getYBodyRot(); + + void setYHeadRot(float var1); + + void setXHeadRot(float var1); + + void setYBodyRot(float var1); + + void setYHeadRotImmediately(float var1); + + void setXHeadRotImmediately(float var1); + + void setYBodyRotImmediately(float var1); + + void setRotationTick(int var1); + + Optional addModel(@NotNull ActiveModel var1, boolean var2); + + Optional removeModel(String var1); + + Optional getModel(@Nullable String var1); + + Map getModels(); + + GlobalBehaviorData getOrCreateGlobalBehaviorData(BoneBehaviorType var1, Supplier var2); + + GlobalBehaviorData getGlobalBehaviorData(BoneBehaviorType var1); + + GlobalBehaviorData removeGlobalBehaviorData(BoneBehaviorType var1); + + Map, GlobalBehaviorData> getAllGlobalBehaviorData(BoneBehaviorType var1); + + T getMountData(); + + RootMotionHandler getRootMotionHandler(); + + boolean isPivotOverride(int var1); + + UUID registerTickTask(ModeledEntity.Phase var1, Function var2); + + UUID registerTickTask(ModeledEntity.Phase var1, Consumer var2); + + void removeTickTask(UUID var1); + + void runTickTasks(ModeledEntity.Phase var1); + + Callback getDestroyCallback(); + + default void registerSelf() { + ModelEngineAPI.getAPI().getModelUpdaters().registerModeledEntity(this.getBase(), this).ifPresent(ModeledEntity::destroy); + this.getBase().registerData(); + } + + public static enum Phase { + PRE_DATA_SYNC, + PRE_MODEL_TICK, + PRE_MODEL_RENDER, + POST_MODEL_RENDER; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/PivotOverride.java b/api/src/main/java/com/ticxo/modelengine/api/model/PivotOverride.java new file mode 100644 index 0000000..54de933 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/PivotOverride.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.api.model; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import java.util.HashSet; +import java.util.UUID; +import java.util.function.Supplier; +import org.bukkit.entity.Entity; +import org.jetbrains.annotations.NotNull; +import org.joml.Vector3f; + +public class PivotOverride { + private final UUID uuid; + private final int id; + private final Supplier mountOffsetSupplier; + private final CollectionDataTracker passengers = new CollectionDataTracker<>(new HashSet<>()); + private volatile int[] basePassengerSnapshot = new int[0]; + + public void addPassenger(int id) { + this.passengers.add(id); + } + + public void removePassenger(int id) { + this.passengers.remove(id); + } + + public Vector3f getMountOffset() { + return this.mountOffsetSupplier.get(); + } + + public static PivotOverride create(@NotNull Entity entity) { + return new PivotOverride(entity.getUniqueId(), entity.getEntityId(), () -> ModelEngineAPI.getEntityHandler().getPivotOffset(entity)); + } + + public void setBasePassengerSnapshot(int[] basePassengerSnapshot) { + this.basePassengerSnapshot = basePassengerSnapshot; + } + + public UUID getUuid() { + return this.uuid; + } + + public int getId() { + return this.id; + } + + public Supplier getMountOffsetSupplier() { + return this.mountOffsetSupplier; + } + + public CollectionDataTracker getPassengers() { + return this.passengers; + } + + public int[] getBasePassengerSnapshot() { + return this.basePassengerSnapshot; + } + + public PivotOverride(UUID uuid, int id, Supplier mountOffsetSupplier) { + this.uuid = uuid; + this.id = id; + this.mountOffsetSupplier = mountOffsetSupplier; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/PivotOverrideRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/model/PivotOverrideRegistry.java new file mode 100644 index 0000000..c873437 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/PivotOverrideRegistry.java @@ -0,0 +1,50 @@ +package com.ticxo.modelengine.api.model; + +import com.google.common.collect.Maps; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.bukkit.entity.Entity; + +public class PivotOverrideRegistry { + private final Map overrides = Maps.newConcurrentMap(); + private final Map entityIdLookup = Maps.newConcurrentMap(); + + public Optional get(UUID uuid) { + return Optional.ofNullable(uuid == null ? null : this.overrides.get(uuid)); + } + + public Optional get(int id) { + return Optional.ofNullable(this.entityIdLookup.get(id)).map(this.overrides::get); + } + + public void register(PivotOverride override) { + this.overrides.put(override.getUuid(), override); + this.entityIdLookup.put(override.getId(), override.getUuid()); + } + + public void remove(UUID uuid) { + PivotOverride removed = this.overrides.remove(uuid); + if (removed != null) { + this.entityIdLookup.remove(removed.getId()); + } + } + + public PivotOverride getOrCreate(Entity entity) { + return this.overrides.computeIfAbsent(entity.getUniqueId(), uuid -> { + this.entityIdLookup.put(entity.getEntityId(), uuid); + return PivotOverride.create(entity); + }); + } + + public Set collectDirty() { + return this.overrides.values().stream().filter(override -> override.getPassengers().isDirty()).collect(Collectors.toSet()); + } + + public Collection getAll() { + return this.overrides.values(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/BoneBehaviorTypes.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/BoneBehaviorTypes.java new file mode 100644 index 0000000..4b76dbc --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/BoneBehaviorTypes.java @@ -0,0 +1,27 @@ +package com.ticxo.modelengine.api.model.bone; + +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.type.Ghost; +import com.ticxo.modelengine.api.model.bone.type.Head; +import com.ticxo.modelengine.api.model.bone.type.HeldItem; +import com.ticxo.modelengine.api.model.bone.type.Leash; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.model.bone.type.NameTag; +import com.ticxo.modelengine.api.model.bone.type.PlayerLimb; +import com.ticxo.modelengine.api.model.bone.type.Segment; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.model.bone.type.UserLimb; + +public final class BoneBehaviorTypes { + public static BoneBehaviorType HEAD; + public static BoneBehaviorType GHOST; + public static BoneBehaviorType MOUNT; + public static BoneBehaviorType SUB_HITBOX; + public static BoneBehaviorType NAMETAG; + public static BoneBehaviorType ITEM; + public static BoneBehaviorType SEGMENT; + public static BoneBehaviorType TAIL; + public static BoneBehaviorType LEASH; + public static BoneBehaviorType PLAYER_LIMB; + public static BoneBehaviorType USER_LIMB; +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/BoneItems.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/BoneItems.java new file mode 100644 index 0000000..af3083d --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/BoneItems.java @@ -0,0 +1,170 @@ +package com.ticxo.modelengine.api.model.bone; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.utils.MiscUtils; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.Supplier; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +public class BoneItems { + private static final boolean COPY_FOR_ITERATION_ORDER = !MiscUtils.isJavaVersionOrHigher(21); + private final Map stacks = Maps.newConcurrentMap(); + private final Map toHash = Maps.newConcurrentMap(); + private final DataTracker tracker = new DataTracker<>(this); + private volatile ItemStack[] bakedStacks = new ItemStack[0]; + + public ItemStack getFirst() { + this.prepStacks(); + return this.stacks.entrySet().iterator().next().getValue(); + } + + public Map getItems() { + return new HashMap<>(this.stacks); + } + + private void bakeStacks() { + this.bakedStacks = this.stacks.values().toArray(new ItemStack[0]); + } + + public void forEach(BiConsumer consumer) { + ItemStack[] current = this.bakedStacks; + + for (int i = 0; i < current.length; i++) { + consumer.accept(current[i].hashCode(), current[i]); + } + } + + public void forEach(Consumer consumer) { + this.forEach(consumer, false); + } + + public void forEach(Consumer consumer, boolean markDirty) { + this.forEach(consumer, () -> markDirty); + } + + public void forEach(Consumer consumer, Supplier markDirty) { + ItemStack[] current = this.bakedStacks; + + for (int i = 0; i < current.length; i++) { + consumer.accept(current[i]); + } + + if (markDirty.get()) { + this.rebuildMaps(current); + } + } + + public void forEachMutating(Predicate consumer) { + ItemStack[] current = this.bakedStacks; + boolean dirty = false; + + for (int i = 0; i < current.length; i++) { + dirty |= consumer.test(current[i]); + } + + if (dirty) { + this.rebuildMaps(current); + } + } + + private void rebuildMaps(ItemStack[] current) { + this.stacks.clear(); + this.toHash.clear(); + + for (int i = 0; i < current.length; i++) { + int hash = current[i].hashCode(); + this.stacks.put(hash, current[i]); + this.toHash.put(current[i], hash); + } + + this.bakeStacks(); + this.markDirty(); + } + + public void update(BlueprintBone bone, Color color) { + Set created = bone.getModelData().createItemStack(ItemModelData.context().color(color).build()); + Set items = (Set)(COPY_FOR_ITERATION_ORDER ? new HashSet<>(created) : created); + if (!items.isEmpty() || !this.stacks.isEmpty()) { + this.stacks.clear(); + this.toHash.clear(); + items.forEach(this::addWithoutBaking); + this.bakeStacks(); + } + } + + public void clear() { + if (!this.stacks.isEmpty()) { + this.stacks.clear(); + this.toHash.clear(); + this.markDirty(); + this.bakeStacks(); + } + } + + public void add(ItemStack stack) { + if (this.addWithoutBaking(stack)) { + this.bakeStacks(); + } + } + + private boolean addWithoutBaking(ItemStack stack) { + if (this.toHash.containsKey(stack)) { + return false; + } else { + if (stack == null) { + stack = new ItemStack(Material.AIR); + } + + Integer hash = stack.hashCode(); + this.stacks.put(hash, stack); + this.toHash.put(stack, hash); + this.markDirty(); + return true; + } + } + + public void remove(ItemStack stack) { + if (this.toHash.containsKey(stack)) { + this.stacks.remove(this.toHash.remove(stack)); + this.markDirty(); + this.bakeStacks(); + } + } + + public void markDirty() { + this.tracker.markDirty(); + } + + public void clearDirty() { + this.tracker.clearDirty(); + } + + public boolean isDirty() { + return this.tracker.isDirty(); + } + + public boolean isEqual(Set stackSet) { + return stackSet.equals(this.toHash.keySet()); + } + + private void prepStacks() { + if (this.stacks.isEmpty()) { + this.add(new ItemStack(Material.AIR)); + } + } + + public DataTracker getTracker() { + return this.tracker; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/ManualAnimator.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/ManualAnimator.java new file mode 100644 index 0000000..5b5ed80 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/ManualAnimator.java @@ -0,0 +1,7 @@ +package com.ticxo.modelengine.api.model.bone; + +public interface ManualAnimator { + boolean applyBoneDefaultLocal(); + + void animate(ModelBone var1); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/ModelBone.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/ModelBone.java new file mode 100644 index 0000000..b84b41c --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/ModelBone.java @@ -0,0 +1,226 @@ +package com.ticxo.modelengine.api.model.bone; + +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.utils.OffsetMode; +import com.ticxo.modelengine.api.utils.StepFlag; +import com.ticxo.modelengine.api.utils.data.io.DataIO; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.math.SafeTransform; +import com.ticxo.modelengine.api.utils.math.Transform; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Consumer; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.entity.Display.Billboard; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix4f; +import org.joml.Vector3f; + +public interface ModelBone extends DataIO { + String getUniqueBoneId(); + + String getBoneId(); + + String getCustomId(); + + void setCustomId(String var1); + + ActiveModel getActiveModel(); + + BlueprintBone getBlueprintBone(); + + @Nullable + ModelBone getParent(); + + @Nullable + ModelBone getPivot(); + + void setParent(@Nullable ModelBone var1); + + void setPivot(@Nullable ModelBone var1); + + boolean isPivotOverride(); + + void setPivotLocation(Location var1); + + Location getPivotLocation(); + + Location calculatePivotLocation(); + + Location getBaseLocation(); + + Map getChildren(); + + boolean isRenderer(); + + void setRenderer(boolean var1); + + void addTickDependencies(String... var1); + + void removeTickDependencies(String... var1); + + void clearTickDependencies(); + + Set getTickDependencies(); + + void tick(); + + void lazyTick(); + + boolean isMarkedDestroy(); + + void destroy(); + + float getYaw(); + + void setYaw(float var1); + + void setModelScale(int var1); + + void calculateGlobalTransform(); + + void setManualAnimator(ManualAnimator var1); + + ManualAnimator getManualAnimator(); + + SafeTransform getLocalTransform(); + + SafeTransform getGlobalTransform(); + + Matrix4f getTransformMatrix(); + + boolean hasGlobalRotation(); + + void setHasGlobalRotation(boolean var1); + + @Deprecated + ItemStack getModel(); + + BoneItems getModels(); + + void setModel(BlueprintBone var1); + + void setModel(ItemStack var1); + + void clearModel(); + + DataTracker getModelTracker(); + + Color getDefaultTint(); + + void setDefaultTint(Color var1); + + Color getDamageTint(); + + void setDamageTint(Color var1); + + boolean isEnchanted(); + + void setEnchanted(boolean var1); + + boolean isVisible(); + + void setVisible(boolean var1); + + boolean isScaleHidden(); + + boolean isGlowing(); + + void setGlowing(@Nullable Boolean var1); + + int getGlowColor(); + + void setGlowColor(@Nullable Integer var1); + + @Nullable + Set getGlowAudience(); + + void setGlowAudience(@Nullable Set var1); + + int getBlockLight(); + + void setBlockLight(int var1); + + int getSkyLight(); + + void setSkyLight(int var1); + + Billboard getBillboard(); + + void setBillboard(Billboard var1); + + default int getBrightness() { + int blockLight = this.getBlockLight(); + int skyLight = this.getSkyLight(); + if (blockLight < 0 && skyLight < 0) { + return -1; + } else { + blockLight = Math.max(blockLight, 0); + skyLight = Math.max(skyLight, 0); + return blockLight << 4 | skyLight << 20; + } + } + + boolean isEffectivelyInvisible(); + + boolean shouldStep(); + + void markStep(StepFlag var1, String var2, float var3); + + int getSubTickSamples(); + + void setSubTickSamples(int var1); + + @Nullable + Transform getSubTickTransform(int var1); + + @Nullable + Matrix4f getSubTickMatrix(int var1); + + @Nullable + Location getSubTickLocation(int var1); + + @Nullable + Location getSubTickLocation(int var1, OffsetMode var2, Vector3f var3, boolean var4); + + boolean isSubTickStep(int var1); + + boolean pollModelScaleChanged(); + + boolean isRootBone(); + + void setBoneOnGround(boolean var1); + + Location getLocationUnsafe(); + + Location getLocation(); + + default Location getLocation(OffsetMode mode, Vector3f offset, boolean scale) { + return this.getLocation(mode, offset, scale, true); + } + + Location getLocation(OffsetMode var1, Vector3f var2, boolean var3, boolean var4); + + void addBoneBehavior(BoneBehavior var1); + + boolean hasBoneBehavior(BoneBehaviorType var1); + + Optional getBoneBehavior(BoneBehaviorType var1); + + Optional removeBoneBehavior(BoneBehaviorType var1); + + Map, BoneBehavior> getImmutableBoneBehaviors(); + + void forBehaviors(Consumer var1); + + default boolean hasBoneBehaviors() { + return !this.getImmutableBoneBehaviors().isEmpty(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/SimpleManualAnimator.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/SimpleManualAnimator.java new file mode 100644 index 0000000..50f6800 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/SimpleManualAnimator.java @@ -0,0 +1,49 @@ +package com.ticxo.modelengine.api.model.bone; + +import com.ticxo.modelengine.api.utils.math.SafeTransform; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class SimpleManualAnimator implements ManualAnimator { + private final Vector3f position = new Vector3f(); + private final Quaternionf rotation = new Quaternionf(); + private final Vector3f scale = new Vector3f(1.0F); + private final boolean copied; + + public SimpleManualAnimator() { + this.copied = false; + } + + public SimpleManualAnimator(ModelBone bone) { + SafeTransform transform = bone.getLocalTransform(); + this.position.set(transform.getSafePosition()); + this.rotation.set(transform.getSafeLeftQuaternion()); + this.scale.set(transform.getSafeScale()); + this.copied = true; + } + + @Override + public boolean applyBoneDefaultLocal() { + return !this.copied; + } + + @Override + public void animate(ModelBone bone) { + SafeTransform transform = bone.getLocalTransform(); + transform.mutatePosition(vector3f -> vector3f.add(this.position)); + transform.mutateLeftQuaternion(quaternionf -> quaternionf.mul(this.rotation)); + transform.mutateScale(vector3f -> vector3f.mul(this.scale)); + } + + public Vector3f getPosition() { + return this.position; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public Vector3f getScale() { + return this.scale; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/AbstractBoneBehavior.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/AbstractBoneBehavior.java new file mode 100644 index 0000000..4373aa7 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/AbstractBoneBehavior.java @@ -0,0 +1,30 @@ +package com.ticxo.modelengine.api.model.bone.behavior; + +import com.ticxo.modelengine.api.model.bone.ModelBone; + +public abstract class AbstractBoneBehavior implements BoneBehavior { + protected final ModelBone bone; + protected final BoneBehaviorType type; + protected final BoneBehaviorData data; + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public BoneBehaviorType getType() { + return this.type; + } + + @Override + public BoneBehaviorData getData() { + return this.data; + } + + public AbstractBoneBehavior(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + this.bone = bone; + this.type = type; + this.data = data; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehavior.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehavior.java new file mode 100644 index 0000000..56064ae --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehavior.java @@ -0,0 +1,117 @@ +package com.ticxo.modelengine.api.model.bone.behavior; + +import com.ticxo.modelengine.api.events.BoneTransformReadEvent; +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 org.jetbrains.annotations.Nullable; + +public interface BoneBehavior extends DataIO { + ModelBone getBone(); + + BoneBehaviorType getType(); + + BoneBehaviorData getData(); + + default void onApply() { + } + + default void onRemove() { + } + + default void onModelInitialized() { + } + + default void onParentSwap(@Nullable ModelBone parent) { + } + + default void preAnimation() { + } + + default void onAnimation() { + } + + default void postAnimation() { + } + + default void onGlobalCalculation() { + } + + default void preGlobalCalculation() { + } + + default void preGlobalTranslate() { + } + + default void postGlobalTranslate() { + } + + default void preGlobalRotate() { + } + + default void postGlobalRotate() { + } + + default void preGlobalScale() { + } + + default void postGlobalScale() { + } + + default void preGlobalShear() { + } + + default void postGlobalShear() { + } + + default void postGlobalCalculation() { + } + + default void preTransformDecompose() { + } + + default void postTransformDecompose() { + } + + default void postTransformRecompose() { + } + + default float onUpdateYaw(float yaw) { + return yaw; + } + + @Deprecated + default void preChildCalculation() { + } + + @Deprecated + default void postChildCalculation() { + } + + default void onFinalize() { + } + + default void modifyTransform(BoneTransformReadEvent event) { + } + + default void preRender() { + } + + default void onRender() { + } + + default void postRender() { + } + + default boolean isHidden() { + return false; + } + + @Override + default void save(SavedData data) { + } + + @Override + default void load(SavedData data) { + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorData.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorData.java new file mode 100644 index 0000000..ea12a45 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorData.java @@ -0,0 +1,41 @@ +package com.ticxo.modelengine.api.model.bone.behavior; + +import java.util.Map; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class BoneBehaviorData { + private final Map data; + + @Nullable + public T get(String key) { + try { + return (T)this.data.get(key); + } catch (ClassCastException var3) { + var3.printStackTrace(); + return null; + } + } + + @NotNull + public T get(String key, @NotNull T def) { + Object value = this.data.get(key); + if (value == null) { + return def; + } else { + Class defClass = def.getClass(); + Class valClass = value.getClass(); + if (defClass.isAssignableFrom(valClass)) { + return (T)value; + } else { + new ClassCastException(String.format("Could not cast %s to %s. Returning default value.", valClass.getSimpleName(), defClass.getSimpleName())) + .printStackTrace(); + return def; + } + } + } + + public BoneBehaviorData(Map data) { + this.data = data; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorRegistry.java new file mode 100644 index 0000000..e86dd75 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorRegistry.java @@ -0,0 +1,37 @@ +package com.ticxo.modelengine.api.model.bone.behavior; + +import com.google.common.collect.ImmutableSet; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import org.jetbrains.annotations.Nullable; + +public class BoneBehaviorRegistry { + private final Map> idRegistry = new HashMap<>(); + private Gson gson; + + public void register(BoneBehaviorType type) { + this.idRegistry.put(type.getId(), type); + } + + @Nullable + public BoneBehaviorType getById(String id) { + return this.idRegistry.get(id); + } + + public Set getIds() { + return ImmutableSet.copyOf(this.idRegistry.keySet()); + } + + public Gson getGson() { + if (this.gson == null) { + GsonBuilder builder = new GsonBuilder(); + this.idRegistry.forEach((s, boneBehaviorType) -> boneBehaviorType.getDataDeserializer().forEach(builder::registerTypeAdapter)); + this.gson = builder.create(); + } + + return this.gson; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorType.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorType.java new file mode 100644 index 0000000..c19e3fd --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/BoneBehaviorType.java @@ -0,0 +1,300 @@ +package com.ticxo.modelengine.api.model.bone.behavior; + +import com.google.gson.JsonDeserializer; +import com.ticxo.modelengine.api.error.ErrorMissingBoneBehaviorData; +import com.ticxo.modelengine.api.error.ErrorWrongBoneBehaviorDataType; +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.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.render.DefaultRenderType; +import com.ticxo.modelengine.api.model.bone.render.IRenderType; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; +import java.util.function.Predicate; +import org.jetbrains.annotations.Nullable; + +public class BoneBehaviorType { + private final BoneBehaviorType.BehaviorProvider behaviorProvider; + private final BoneBehaviorType.BehaviorManagerProvider behaviorManagerProvider; + private final String id; + private final Map> requiredArguments; + private final Map> optionalArguments; + private final Map, JsonDeserializer> dataDeserializer; + private final IRenderType renderType; + private final Set proceduralTypes; + private final Predicate>> predicate; + private final BoneBehaviorType.BehaviorProvider forcedBehaviorProvider; + private final boolean ignoreCubes; + private final boolean pivot; + + public void assignCachedProvider(BlueprintBone bone, Map data) { + Map verifiedData = new HashMap<>(); + + for (Entry> entry : this.requiredArguments.entrySet()) { + String key = entry.getKey(); + Class clazz = entry.getValue(); + Object value = data.get(key); + if (value == null) { + new ErrorMissingBoneBehaviorData(bone.getName(), this, key); + return; + } + + if (!clazz.isAssignableFrom(value.getClass())) { + new ErrorWrongBoneBehaviorDataType(bone.getName(), this, key, clazz, value.getClass()); + return; + } + + verifiedData.put(key, value); + } + + for (Entry> entry : this.optionalArguments.entrySet()) { + String keyx = entry.getKey(); + Class clazzx = entry.getValue(); + Object valuex = data.get(keyx); + if (valuex != null) { + if (!clazzx.isAssignableFrom(valuex.getClass())) { + new ErrorWrongBoneBehaviorDataType(bone.getName(), this, keyx, clazzx, valuex.getClass()); + return; + } + + verifiedData.put(keyx, valuex); + } + } + + bone.getCachedBehaviorProvider().put(this, new BoneBehaviorType.CachedProvider<>(this.behaviorProvider, this, new BoneBehaviorData(verifiedData))); + } + + public void assignForcedCachedProvider(BlueprintBone bone) { + if (this.forcedBehaviorProvider != null) { + if (!bone.getCachedBehaviorProvider().containsKey(this)) { + bone.getCachedBehaviorProvider() + .put(this, new BoneBehaviorType.CachedProvider<>(this.forcedBehaviorProvider, this, new BoneBehaviorData(new HashMap<>()))); + } + } + } + + public boolean test(Set> types) { + return this.predicate.test(types); + } + + public static boolean noProcedural(Set> types) { + for (BoneBehaviorType type : types) { + if (!type.getProceduralTypes().isEmpty()) { + return false; + } + } + + return true; + } + + public BoneBehaviorType.BehaviorProvider getBehaviorProvider() { + return this.behaviorProvider; + } + + public BoneBehaviorType.BehaviorManagerProvider getBehaviorManagerProvider() { + return this.behaviorManagerProvider; + } + + public String getId() { + return this.id; + } + + public Map> getRequiredArguments() { + return this.requiredArguments; + } + + public Map> getOptionalArguments() { + return this.optionalArguments; + } + + public Map, JsonDeserializer> getDataDeserializer() { + return this.dataDeserializer; + } + + public IRenderType getRenderType() { + return this.renderType; + } + + public Set getProceduralTypes() { + return this.proceduralTypes; + } + + public Predicate>> getPredicate() { + return this.predicate; + } + + public BoneBehaviorType.BehaviorProvider getForcedBehaviorProvider() { + return this.forcedBehaviorProvider; + } + + public boolean isIgnoreCubes() { + return this.ignoreCubes; + } + + public boolean isPivot() { + return this.pivot; + } + + protected BoneBehaviorType( + BoneBehaviorType.BehaviorProvider behaviorProvider, + BoneBehaviorType.BehaviorManagerProvider behaviorManagerProvider, + String id, + Map> requiredArguments, + Map> optionalArguments, + Map, JsonDeserializer> dataDeserializer, + IRenderType renderType, + Set proceduralTypes, + Predicate>> predicate, + BoneBehaviorType.BehaviorProvider forcedBehaviorProvider, + boolean ignoreCubes, + boolean pivot + ) { + this.behaviorProvider = behaviorProvider; + this.behaviorManagerProvider = behaviorManagerProvider; + this.id = id; + this.requiredArguments = requiredArguments; + this.optionalArguments = optionalArguments; + this.dataDeserializer = dataDeserializer; + this.renderType = renderType; + this.proceduralTypes = proceduralTypes; + this.predicate = predicate; + this.forcedBehaviorProvider = forcedBehaviorProvider; + this.ignoreCubes = ignoreCubes; + this.pivot = pivot; + } + + @FunctionalInterface + public interface BehaviorManagerProvider { + BehaviorManager create(ActiveModel var1, BoneBehaviorType var2); + } + + @FunctionalInterface + public interface BehaviorProvider { + T create(ModelBone var1, BoneBehaviorType var2, BoneBehaviorData var3); + } + + public static class Builder { + private final BoneBehaviorType.BehaviorProvider behaviorProvider; + private final BoneBehaviorType.BehaviorManagerProvider behaviorManagerProvider; + private final String id; + private final Map> requiredArguments = new HashMap<>(); + private final Map> optionalArguments = new HashMap<>(); + private final Map, JsonDeserializer> dataDeserializer = new HashMap<>(); + private final Set proceduralTypes = new HashSet<>(); + private IRenderType renderType = DefaultRenderType.ANY; + private Predicate>> predicate = boneBehaviorTypes -> true; + private BoneBehaviorType.BehaviorProvider forcedBehaviorProvider; + private boolean ignoreCubes; + private boolean pivot; + + public static BoneBehaviorType.Builder of( + BoneBehaviorType.BehaviorProvider behaviorProvider, @Nullable BoneBehaviorType.BehaviorManagerProvider behaviorManagerProvider, String id + ) { + return new BoneBehaviorType.Builder<>(behaviorProvider, behaviorManagerProvider, id); + } + + public BoneBehaviorType.Builder required(String key, Class type) { + this.requiredArguments.put(key, type); + return this; + } + + public BoneBehaviorType.Builder required(String key, Class type, JsonDeserializer deserializer) { + this.requiredArguments.put(key, type); + this.dataDeserializer.put(type, deserializer); + return this; + } + + public BoneBehaviorType.Builder optional(String key, Class type) { + this.optionalArguments.put(key, type); + return this; + } + + public BoneBehaviorType.Builder optional(String key, Class type, JsonDeserializer deserializer) { + this.optionalArguments.put(key, type); + this.dataDeserializer.put(type, deserializer); + return this; + } + + public BoneBehaviorType.Builder renderType(IRenderType type) { + this.renderType = type; + return this; + } + + public BoneBehaviorType.Builder procedural(ProceduralType... types) { + this.proceduralTypes.addAll(Arrays.asList(types)); + return this; + } + + public BoneBehaviorType.Builder predicate(Predicate>> predicate) { + this.predicate = predicate; + return this; + } + + public BoneBehaviorType.Builder forced(BoneBehaviorType.BehaviorProvider forcedBehaviorProvider) { + this.forcedBehaviorProvider = forcedBehaviorProvider; + return this; + } + + public BoneBehaviorType.Builder ignoreCubes() { + this.ignoreCubes = true; + return this; + } + + public BoneBehaviorType.Builder pivot() { + this.pivot = true; + return this; + } + + public BoneBehaviorType build() { + return new BoneBehaviorType<>( + this.behaviorProvider, + this.behaviorManagerProvider, + this.id, + this.requiredArguments, + this.optionalArguments, + this.dataDeserializer, + this.renderType, + this.proceduralTypes, + this.predicate, + this.forcedBehaviorProvider, + this.ignoreCubes, + this.pivot + ); + } + + protected Builder(BoneBehaviorType.BehaviorProvider behaviorProvider, BoneBehaviorType.BehaviorManagerProvider behaviorManagerProvider, String id) { + this.behaviorProvider = behaviorProvider; + this.behaviorManagerProvider = behaviorManagerProvider; + this.id = id; + } + } + + public static class CachedProvider { + private final BoneBehaviorType.BehaviorProvider behaviorProvider; + private final BoneBehaviorType type; + private final BoneBehaviorData data; + + public T create(ModelBone bone) { + return this.behaviorProvider.create(bone, this.type, this.data); + } + + public CachedProvider(BoneBehaviorType.BehaviorProvider behaviorProvider, BoneBehaviorType type, BoneBehaviorData data) { + this.behaviorProvider = behaviorProvider; + this.type = type; + this.data = data; + } + + public BoneBehaviorType getType() { + return this.type; + } + + public BoneBehaviorData getData() { + return this.data; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/GlobalBehaviorData.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/GlobalBehaviorData.java new file mode 100644 index 0000000..f2865c1 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/GlobalBehaviorData.java @@ -0,0 +1,4 @@ +package com.ticxo.modelengine.api.model.bone.behavior; + +public interface GlobalBehaviorData { +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/ProceduralType.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/ProceduralType.java new file mode 100644 index 0000000..ec3271f --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/behavior/ProceduralType.java @@ -0,0 +1,6 @@ +package com.ticxo.modelengine.api.model.bone.behavior; + +public enum ProceduralType { + ANIMATION, + TRANSFORM; +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/AbstractBehaviorManager.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/AbstractBehaviorManager.java new file mode 100644 index 0000000..f487446 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/AbstractBehaviorManager.java @@ -0,0 +1,32 @@ +package com.ticxo.modelengine.api.model.bone.manager; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import java.util.Optional; + +public abstract class AbstractBehaviorManager implements BehaviorManager { + protected final ActiveModel activeModel; + protected final BoneBehaviorType type; + + protected Optional getBoneBehavior(String boneId) { + Optional bone = this.getActiveModel().getBone(boneId); + return bone.isEmpty() ? Optional.empty() : bone.get().getBoneBehavior(this.getType()); + } + + @Override + public ActiveModel getActiveModel() { + return this.activeModel; + } + + @Override + public BoneBehaviorType getType() { + return this.type; + } + + public AbstractBehaviorManager(ActiveModel activeModel, BoneBehaviorType type) { + this.activeModel = activeModel; + this.type = type; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/BehaviorManager.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/BehaviorManager.java new file mode 100644 index 0000000..7ea1932 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/BehaviorManager.java @@ -0,0 +1,45 @@ +package com.ticxo.modelengine.api.model.bone.manager; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.utils.data.io.DataIO; +import com.ticxo.modelengine.api.utils.data.io.SavedData; + +public interface BehaviorManager extends DataIO { + ActiveModel getActiveModel(); + + BoneBehaviorType getType(); + + default void onCreate() { + } + + default void onDestroy() { + } + + default void preBoneTick() { + } + + default void postBoneTick() { + } + + default void preScriptTick() { + } + + default void postScriptTick() { + } + + default void preBoneRender() { + } + + default void postBoneRender() { + } + + @Override + default void load(SavedData data) { + } + + @Override + default void save(SavedData data) { + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/LeashManager.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/LeashManager.java new file mode 100644 index 0000000..c3a513b --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/LeashManager.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.api.model.bone.manager; + +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.type.Leash; +import java.util.Map; +import java.util.Optional; +import org.bukkit.entity.Entity; + +public interface LeashManager { + void registerLeash(T var1); + + Map getMainLeashes(); + + Map getLeashes(); + + Optional getLeash(String var1); + + void connectMainLeashes(Entity var1); + + void connectMainLeashes(String var1); + + void disconnectMainLeashes(); + + void connectLeash(Entity var1, String var2); + + void connectLeash(String var1, String var2); + + void disconnect(String var1); + + Entity getLeashHolder(String var1); + + T getLeashConnection(String var1); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/MountData.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/MountData.java new file mode 100644 index 0000000..70e9d1e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/MountData.java @@ -0,0 +1,9 @@ +package com.ticxo.modelengine.api.model.bone.manager; + +import com.ticxo.modelengine.api.model.bone.type.Mount; + +public interface MountData { + & MountManager> T getMainMountManager(); + + & MountManager> void setMainMountManager(T var1); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/MountManager.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/MountManager.java new file mode 100644 index 0000000..62afde4 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/manager/MountManager.java @@ -0,0 +1,101 @@ +package com.ticxo.modelengine.api.model.bone.manager; + +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.mount.controller.MountControllerSupplier; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import org.bukkit.entity.Entity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface MountManager { + void setCanDrive(boolean var1); + + boolean canDrive(); + + void setCanRide(boolean var1); + + boolean canRide(); + + Entity getDriver(); + + boolean isControlled(); + + boolean hasPassengers(); + + boolean hasRiders(); + + @Nullable + T getDriverBone(); + + void setDriverBone(@Nullable T var1); + + void registerSeat(T var1); + + Map getSeats(); + + Optional getSeat(String var1); + + Optional getMount(Entity var1); + + Map getPassengerSeatMap(); + + boolean mountDriver(Entity var1, MountControllerSupplier var2); + + boolean mountDriver(Entity var1, MountControllerSupplier var2, @Nullable Consumer var3); + + boolean mountPassenger(String var1, Entity var2, MountControllerSupplier var3); + + boolean mountPassenger(String var1, Entity var2, MountControllerSupplier var3, @Nullable Consumer var4); + + boolean mountPassenger(Mount var1, Entity var2, MountControllerSupplier var3); + + boolean mountPassenger(Mount var1, Entity var2, MountControllerSupplier var3, @Nullable Consumer var4); + + boolean mountAvailable(Entity var1, MountControllerSupplier var2); + + boolean mountAvailable(Entity var1, MountControllerSupplier var2, @Nullable Consumer var3); + + Set mountAvailable(Collection var1, MountControllerSupplier var2); + + Set mountAvailable(Collection var1, MountControllerSupplier var2, @Nullable Consumer var3); + + boolean mountAvailable(Entity var1, Collection var2, MountControllerSupplier var3); + + boolean mountAvailable(Entity var1, Collection var2, MountControllerSupplier var3, @Nullable Consumer var4); + + Set mountAvailable(Collection var1, Collection var2, MountControllerSupplier var3); + + Set mountAvailable(Collection var1, Collection var2, MountControllerSupplier var3, @Nullable Consumer var4); + + boolean mountLeastOccupied(Entity var1, MountControllerSupplier var2); + + boolean mountLeastOccupied(Entity var1, MountControllerSupplier var2, @Nullable Consumer var3); + + Set mountLeastOccupied(Collection var1, MountControllerSupplier var2); + + Set mountLeastOccupied(Collection var1, MountControllerSupplier var2, @Nullable Consumer var3); + + boolean mountLeastOccupied(Entity var1, Collection var2, MountControllerSupplier var3); + + boolean mountLeastOccupied(Entity var1, Collection var2, MountControllerSupplier var3, @Nullable Consumer var4); + + Set mountLeastOccupied(Collection var1, Collection var2, MountControllerSupplier var3); + + Set mountLeastOccupied(Collection var1, Collection var2, MountControllerSupplier var3, @Nullable Consumer var4); + + Entity dismountDriver(); + + void dismountPassenger(@NotNull Entity var1); + + void dismountRider(@NotNull Entity var1); + + Set dismountPassengers(String var1); + + Set dismountAll(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/BehaviorRenderer.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/BehaviorRenderer.java new file mode 100644 index 0000000..9d70ebf --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/BehaviorRenderer.java @@ -0,0 +1,31 @@ +package com.ticxo.modelengine.api.model.bone.render; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.utils.data.io.DataIO; +import com.ticxo.modelengine.api.utils.data.io.SavedData; + +public interface BehaviorRenderer extends DataIO { + ModelRenderer getModelRenderer(); + + void setModelRenderer(ModelRenderer var1); + + ActiveModel getActiveModel(); + + void initialize(); + + void readBoneData(); + + void sendToClient(RenderParsers var1); + + void destroy(RenderParsers var1); + + @Override + default void load(SavedData data) { + } + + @Override + default void save(SavedData data) { + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/BehaviorRendererParser.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/BehaviorRendererParser.java new file mode 100644 index 0000000..1ff65df --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/BehaviorRendererParser.java @@ -0,0 +1,7 @@ +package com.ticxo.modelengine.api.model.bone.render; + +public interface BehaviorRendererParser { + void sendToClients(T var1); + + void destroy(T var1); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/DefaultRenderType.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/DefaultRenderType.java new file mode 100644 index 0000000..9edd767 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/DefaultRenderType.java @@ -0,0 +1,16 @@ +package com.ticxo.modelengine.api.model.bone.render; + +import com.ticxo.modelengine.api.model.ActiveModel; +import org.jetbrains.annotations.Nullable; + +public enum DefaultRenderType implements IRenderType { + ANY, + NONE, + MODEL; + + @Nullable + @Override + public BehaviorRenderer createBehaviorRenderer(ActiveModel activeModel) { + return null; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/IRenderType.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/IRenderType.java new file mode 100644 index 0000000..750324f --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/IRenderType.java @@ -0,0 +1,9 @@ +package com.ticxo.modelengine.api.model.bone.render; + +import com.ticxo.modelengine.api.model.ActiveModel; +import org.jetbrains.annotations.Nullable; + +public interface IRenderType { + @Nullable + BehaviorRenderer createBehaviorRenderer(ActiveModel var1); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/HeldItemRenderer.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/HeldItemRenderer.java new file mode 100644 index 0000000..cb2cf21 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/HeldItemRenderer.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.api.model.bone.render.renderer; + +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.UUID; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.bukkit.inventory.ItemStack; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public interface HeldItemRenderer extends BehaviorRenderer, RenderQueues { + int getId(); + + UUID getUuid(); + + CollectionDataTracker getPassengers(); + + default PositionCodec getPositionCodec() { + return null; + } + + public interface Item { + int getId(); + + UUID getUuid(); + + DataTracker getPosition(); + + DataTracker getScale(); + + DataTracker getRotation(); + + DataTracker getModel(); + + DataTracker getDisplay(); + + DataTracker getGlowing(); + + DataTracker getGlowColor(); + + default boolean isTransformDirty() { + return this.getPosition().isDirty() || this.getScale().isDirty() || this.getRotation().isDirty(); + } + + default boolean isRenderDirty() { + return this.getModel().isDirty() || this.getDisplay().isDirty() || this.getGlowing().isDirty() || this.getGlowColor().isDirty(); + } + + default boolean isDirty() { + return this.isTransformDirty() || this.isRenderDirty(); + } + + default void clearDirty() { + this.getPosition().clearDirty(); + this.getScale().clearDirty(); + this.getRotation().clearDirty(); + this.getModel().clearDirty(); + this.getDisplay().clearDirty(); + this.getGlowing().clearDirty(); + this.getGlowColor().clearDirty(); + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/LeashRenderer.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/LeashRenderer.java new file mode 100644 index 0000000..1bdf524 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/LeashRenderer.java @@ -0,0 +1,27 @@ +package com.ticxo.modelengine.api.model.bone.render.renderer; + +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.UUID; +import org.joml.Vector3f; + +public interface LeashRenderer extends BehaviorRenderer, RenderQueues { + public interface Leash { + int getPivotId(); + + UUID getPivotUUID(); + + int getLeashId(); + + UUID getLeastUUID(); + + DataTracker getPosition(); + + DataTracker getConnected(); + + default PositionCodec getPositionCodec() { + return null; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/MountRenderer.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/MountRenderer.java new file mode 100644 index 0000000..726211b --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/MountRenderer.java @@ -0,0 +1,29 @@ +package com.ticxo.modelengine.api.model.bone.render.renderer; + +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.UUID; +import org.joml.Vector3f; + +public interface MountRenderer extends BehaviorRenderer, RenderQueues { + public interface Mount { + int getPivotId(); + + UUID getPivotUuid(); + + int getMountId(); + + UUID getMountUuid(); + + DataTracker getPosition(); + + DataTracker getYaw(); + + DataTracker getMaxHealth(); + + DataTracker getHealth(); + + CollectionDataTracker getPassengers(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/NameTagRenderer.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/NameTagRenderer.java new file mode 100644 index 0000000..6ef45c3 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/NameTagRenderer.java @@ -0,0 +1,74 @@ +package com.ticxo.modelengine.api.model.bone.render.renderer; + +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.UUID; +import org.bukkit.entity.Display.Billboard; +import org.joml.Vector3f; + +public interface NameTagRenderer extends BehaviorRenderer, RenderQueues { + public interface NameTag { + int DEFAULT_BACKGROUND_COLOR = 1073741824; + + int getPivotId(); + + UUID getPivotUuid(); + + int getTagId(); + + UUID getTagUuid(); + + DataTracker getPosition(); + + DataTracker getJsonString(); + + DataTracker getVisibility(); + + DataTracker getBackgroundColor(); + + DataTracker getBillboard(); + + DataTracker getTextOpacity(); + + DataTracker getLineWidth(); + + DataTracker getTranslate(); + + DataTracker getScale(); + + DataTracker getStyle(); + + DataTracker getBrightness(); + + default PositionCodec getPositionCodec() { + return null; + } + + default boolean isDirty() { + return this.getJsonString().isDirty() + || this.getVisibility().isDirty() + || this.getBillboard().isDirty() + || this.getBackgroundColor().isDirty() + || this.getTextOpacity().isDirty() + || this.getLineWidth().isDirty() + || this.getStyle().isDirty() + || this.getTranslate().isDirty() + || this.getScale().isDirty() + || this.getBrightness().isDirty(); + } + + default void clearDirty() { + this.getJsonString().clearDirty(); + this.getVisibility().clearDirty(); + this.getBillboard().clearDirty(); + this.getBackgroundColor().clearDirty(); + this.getTextOpacity().clearDirty(); + this.getLineWidth().clearDirty(); + this.getTranslate().clearDirty(); + this.getScale().clearDirty(); + this.getStyle().clearDirty(); + this.getBrightness().clearDirty(); + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/RenderQueues.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/RenderQueues.java new file mode 100644 index 0000000..72b9c4e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/RenderQueues.java @@ -0,0 +1,23 @@ +package com.ticxo.modelengine.api.model.bone.render.renderer; + +import java.util.Map; + +public interface RenderQueues { + Map getSpawnQueue(); + + Map getRendered(); + + Map getDestroyQueue(); + + default T getQueued(String id) { + Map sq = this.getSpawnQueue(); + if (!sq.isEmpty()) { + T queued = sq.get(id); + if (queued != null) { + return queued; + } + } + + return this.getRendered().get(id); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/SegmentRenderer.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/SegmentRenderer.java new file mode 100644 index 0000000..a38c5a7 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/SegmentRenderer.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.api.model.bone.render.renderer; + +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.UUID; +import org.joml.Vector3f; + +public interface SegmentRenderer extends BehaviorRenderer, RenderQueues { + public interface Pivot extends RenderQueues { + int getId(); + + UUID getUuid(); + + void clearDirty(); + + DataTracker getPosition(); + + DataTracker getYaw(); + + CollectionDataTracker getPassengers(); + + default PositionCodec getPositionCodec() { + return null; + } + } + + public interface SegmentDisplayBone extends DisplayBone { + SegmentRenderer.Pivot getPivot(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/SubHitboxRenderer.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/SubHitboxRenderer.java new file mode 100644 index 0000000..46aa049 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/render/renderer/SubHitboxRenderer.java @@ -0,0 +1,38 @@ +package com.ticxo.modelengine.api.model.bone.render.renderer; + +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.UUID; +import org.joml.Vector3f; + +public interface SubHitboxRenderer extends BehaviorRenderer, RenderQueues { + public interface SubHitbox { + int getPivotId(); + + int getHitboxId(); + + UUID getPivotUuid(); + + UUID getHitboxUuid(); + + DataTracker getPosition(); + + DataTracker getWidth(); + + DataTracker getHeight(); + + default PositionCodec getPositionCodec() { + return null; + } + + default boolean isDirty() { + return this.getWidth().isDirty() || this.getHeight().isDirty(); + } + + default void clearDirty() { + this.getWidth().clearDirty(); + this.getHeight().clearDirty(); + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Ghost.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Ghost.java new file mode 100644 index 0000000..791a670 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Ghost.java @@ -0,0 +1,7 @@ +package com.ticxo.modelengine.api.model.bone.type; + +import com.ticxo.modelengine.api.model.bone.BoneItems; + +public interface Ghost { + BoneItems getModel(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Head.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Head.java new file mode 100644 index 0000000..696fee1 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Head.java @@ -0,0 +1,7 @@ +package com.ticxo.modelengine.api.model.bone.type; + +public interface Head { + boolean isLocal(); + + void setLocal(boolean var1); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/HeldItem.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/HeldItem.java new file mode 100644 index 0000000..4a125b7 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/HeldItem.java @@ -0,0 +1,140 @@ +package com.ticxo.modelengine.api.model.bone.type; + +import com.ticxo.modelengine.api.utils.data.io.DataIO; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.UUID; +import java.util.function.Supplier; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.bukkit.inventory.EntityEquipment; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public interface HeldItem { + ItemStack EMPTY = new ItemStack(Material.AIR); + + Vector3f getLocation(); + + Quaternionf getRotation(); + + ItemDisplayTransform getDisplay(); + + void setDisplay(ItemDisplayTransform var1); + + HeldItem.ItemStackSupplier getItemProvider(); + + void setItemProvider(Supplier var1); + + void setItemProvider(HeldItem.ItemStackSupplier var1); + + void clearItemProvider(); + + ItemStack getItem(); + + public static class EquipmentSupplier implements HeldItem.ItemStackSupplier { + private LivingEntity target; + private EquipmentSlot slot; + + public EquipmentSupplier() { + } + + @Override + public ItemStack supply() { + if (this.target != null && this.slot != null) { + EntityEquipment eq = this.target.getEquipment(); + return eq == null ? HeldItem.EMPTY : eq.getItem(this.slot); + } else { + return HeldItem.EMPTY; + } + } + + @Override + public void save(SavedData data) { + data.putString("type", "equipment"); + data.putUUID("target", this.target.getUniqueId()); + data.put("slot", this.slot.name()); + } + + @Override + public void load(SavedData data) { + UUID uuid = data.getUUID("target"); + String slotString = data.getString("slot"); + if (uuid != null && slotString != null) { + if (Bukkit.getEntity(uuid) instanceof LivingEntity livingEntity) { + try { + this.slot = EquipmentSlot.valueOf(slotString); + } catch (Throwable var7) { + TLogger.error(1, "Failed to load EquipmentSupplier: Invalid slot " + slotString + "."); + return; + } + + this.target = livingEntity; + } else { + TLogger.error(1, "Failed to load EquipmentSupplier: Target entity does not exist or is not LivingEntity."); + } + } + } + + public EquipmentSupplier(LivingEntity target, EquipmentSlot slot) { + this.target = target; + this.slot = slot; + } + } + + public interface ItemStackSupplier extends DataIO { + ItemStack supply(); + } + + public static class StaticItemStackSupplier implements HeldItem.ItemStackSupplier { + private ItemStack itemStack; + + public StaticItemStackSupplier() { + } + + @Override + public ItemStack supply() { + return this.itemStack; + } + + @Override + public void save(SavedData data) { + data.putString("type", "static"); + data.putItemStack("item", this.itemStack); + } + + @Override + public void load(SavedData data) { + this.itemStack = data.getItemStack("item", HeldItem.EMPTY); + } + + public StaticItemStackSupplier(ItemStack itemStack) { + this.itemStack = itemStack; + } + } + + public static class TemporaryItemStackSupplier implements HeldItem.ItemStackSupplier { + private final Supplier stackSupplier; + + @Override + public ItemStack supply() { + return this.stackSupplier.get(); + } + + @Override + public void save(SavedData data) { + } + + @Override + public void load(SavedData data) { + } + + public TemporaryItemStackSupplier(Supplier stackSupplier) { + this.stackSupplier = stackSupplier; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Leash.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Leash.java new file mode 100644 index 0000000..c84e268 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Leash.java @@ -0,0 +1,23 @@ +package com.ticxo.modelengine.api.model.bone.type; + +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import org.bukkit.entity.Entity; +import org.joml.Vector3f; + +public interface Leash { + boolean isMainLeash(); + + int getId(); + + Vector3f getLocation(); + + void connect(Entity var1); + + void connect(T var1); + + void disconnect(); + + Entity getConnectedEntity(); + + T getConnectedLeash(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Mount.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Mount.java new file mode 100644 index 0000000..ce764b9 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Mount.java @@ -0,0 +1,28 @@ +package com.ticxo.modelengine.api.model.bone.type; + +import java.util.Collection; +import java.util.Set; +import org.bukkit.entity.Entity; +import org.joml.Vector3f; + +public interface Mount { + boolean isDriver(); + + Vector3f getLocation(); + + Vector3f getGlobalLocation(); + + boolean addPassenger(Entity var1); + + boolean addPassengers(Collection var1); + + void removePassenger(Entity var1); + + void removePassengers(Collection var1); + + Set clearPassengers(); + + Set getPassengers(); + + boolean canMountMore(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/NameTag.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/NameTag.java new file mode 100644 index 0000000..bc95368 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/NameTag.java @@ -0,0 +1,71 @@ +package com.ticxo.modelengine.api.model.bone.type; + +import java.util.function.Supplier; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Display.Billboard; +import org.bukkit.entity.TextDisplay.TextAlignment; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public interface NameTag { + Vector3f getLocation(); + + void setString(String var1); + + void setComponent(Component var1); + + String getJsonString(); + + void setJsonString(String var1); + + void setComponentSupplier(@Nullable Supplier var1); + + @Nullable + Supplier getJsonStringSupplier(); + + void setJsonStringSupplier(@Nullable Supplier var1); + + boolean isVisible(); + + void setVisible(boolean var1); + + void setLineWidth(int var1); + + int getLineWidth(); + + void setBackgroundColor(int var1); + + int getBackgroundColor(); + + void setUseDefaultBackgroundColor(boolean var1); + + boolean isUseDefaultBackgroundColor(); + + void setAlignment(TextAlignment var1); + + TextAlignment getAlignment(); + + void setTextOpacity(byte var1); + + byte getTextOpacity(); + + void setShadow(boolean var1); + + boolean isShadow(); + + void setSeeThrough(boolean var1); + + boolean isSeeThrough(); + + void setBillboard(Billboard var1); + + Billboard getBillboard(); + + void setScale(Vector3f var1); + + Vector3f getScale(); + + void setPosition(Vector3f var1); + + Vector3f getPosition(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/PlayerLimb.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/PlayerLimb.java new file mode 100644 index 0000000..8afdc58 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/PlayerLimb.java @@ -0,0 +1,34 @@ +package com.ticxo.modelengine.api.model.bone.type; + +import com.destroystokyo.paper.profile.PlayerProfile; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public interface PlayerLimb { + void setTexture(@Nullable Player var1); + + void setTexture(@Nullable PlayerProfile var1); + + PlayerLimb.Limb getLimbType(); + + public static enum Limb { + HEAD(0, 1, 0, 1), + RIGHT_ARM(1, 2, 3, 7), + LEFT_ARM(2, 3, 4, 8), + BODY(5, 4, 5, 4), + RIGHT_LEG(6, 5, 6, 5), + LEFT_LEG(7, 6, 7, 6); + + public final float defaultYOffset; + public final int defaultId; + public final float slimYOffset; + public final int slimId; + + private Limb(int defaultYOffset, int defaultId, int slimYOffset, int slimId) { + this.defaultYOffset = defaultYOffset * -1024; + this.defaultId = defaultId; + this.slimYOffset = slimYOffset * -1024; + this.slimId = slimId; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Segment.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Segment.java new file mode 100644 index 0000000..40f3306 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/Segment.java @@ -0,0 +1,45 @@ +package com.ticxo.modelengine.api.model.bone.type; + +import org.joml.Vector3f; + +public interface Segment { + void setBounded(boolean var1); + + boolean isBounded(); + + void setMinX(float var1); + + float getMinX(); + + void setMaxX(float var1); + + float getMaxX(); + + void setMinY(float var1); + + float getMinY(); + + void setMaxY(float var1); + + float getMaxY(); + + void setMinZ(float var1); + + float getMinZ(); + + void setMaxZ(float var1); + + float getMaxZ(); + + void setAlignRate(float var1); + + float getAlignRate(); + + void setElasticity(float var1); + + float getElasticity(); + + Vector3f getWorldLocation(); + + Vector3f getDelta(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/SubHitbox.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/SubHitbox.java new file mode 100644 index 0000000..6c2a6d0 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/SubHitbox.java @@ -0,0 +1,42 @@ +package com.ticxo.modelengine.api.model.bone.type; + +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import java.util.Map; +import java.util.UUID; +import org.bukkit.entity.Entity; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public interface SubHitbox { + boolean isOBB(); + + Vector3f getFixedDimension(); + + Vector3f getOrigin(); + + float getDamageMultiplier(); + + void setDamageMultiplier(float var1); + + boolean isCanBeHitByProjectile(); + + void setCanBeHitByProjectile(boolean var1); + + void addBoundEntity(Entity var1); + + void removeBoundEntity(Entity var1); + + Map getBoundEntities(); + + int getHitboxId(); + + Vector3f getDimension(); + + Vector3f getLocation(); + + Quaternionf getRotation(); + + float getYaw(); + + HitboxEntity getHitboxEntity(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/UserLimb.java b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/UserLimb.java new file mode 100644 index 0000000..bda08bf --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/bone/type/UserLimb.java @@ -0,0 +1,19 @@ +package com.ticxo.modelengine.api.model.bone.type; + +import com.destroystokyo.paper.profile.PlayerProfile; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public interface UserLimb { + void setTexture(@Nullable Player var1); + + void setTexture(@Nullable PlayerProfile var1); + + void setPlaceholder(String var1); + + String getPlaceholder(); + + String getLimbType(); + + void setStaticSkin(boolean var1, @Nullable String var2); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/limb/UserLimbCache.java b/api/src/main/java/com/ticxo/modelengine/api/model/limb/UserLimbCache.java new file mode 100644 index 0000000..9b0b260 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/limb/UserLimbCache.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.api.model.limb; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.generator.skin.SkinGeneratorService; +import com.ticxo.modelengine.api.generator.skin.SkinSplitter; +import com.ticxo.modelengine.api.utils.TFile; +import com.ticxo.modelengine.api.utils.logger.LogColor; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import org.jetbrains.annotations.Nullable; + +public class UserLimbCache { + private final String name; + private final String source; + private final Map classic = new HashMap<>(); + private final Map slim = new HashMap<>(); + private transient Map> requested = Maps.newConcurrentMap(); + private boolean classicGenerated; + private boolean slimGenerated; + + public void initialize() { + if (this.requested == null) { + this.requested = Maps.newConcurrentMap(); + } + } + + public void generate(SkinGeneratorService service, boolean slim) { + this.generate(service, slim, null); + } + + public void generate(SkinGeneratorService service, boolean slim, @Nullable Collection limbTypes) { + if (!service.isEnabled()) { + TLogger.error(2, "Unable to generate user limb cache for " + this.name + ": Service is disabled!."); + } else if (limbTypes == null || !this.isCovered(slim, limbTypes)) { + byte[] imageBytes = Base64.getDecoder().decode(this.source); + SkinSplitter splitter = ModelEngineAPI.getAPI().getSkinSplitter(); + Map skins = limbTypes == null ? splitter.splitSkin(imageBytes, slim) : splitter.splitSkin(imageBytes, slim, limbTypes); + if (!skins.isEmpty()) { + ArrayList> pending = new ArrayList<>(); + synchronized (this) { + for (Entry entry : skins.entrySet()) { + if (!this.getMap(slim).containsKey(entry.getKey()) && !this.requested.containsKey(key(slim, entry.getKey()))) { + this.requested.put(key(slim, entry.getKey()), new CompletableFuture<>()); + pending.add(entry); + } + } + } + + if (!pending.isEmpty()) { + ArrayList> futures = new ArrayList<>(); + AtomicBoolean failed = new AtomicBoolean(); + AtomicBoolean stored = new AtomicBoolean(); + + for (Entry entryx : pending) { + String limbId = entryx.getKey(); + futures.add(service.generate(entryx.getValue()).handle((s, throwable) -> { + CompletableFuture future = this.requested.remove(key(slim, limbId)); + if (throwable != null) { + failed.set(true); + TLogger.warn("Failed to generate skin limb '" + limbId + "' for " + this.name + ": " + describe(throwable)); + if (future != null) { + future.completeExceptionally(throwable); + } + + return null; + } else { + synchronized (this) { + this.getMap(slim).put(limbId, s); + } + + stored.set(true); + if (future != null) { + future.complete(s); + } + + return null; + } + })); + } + + CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).thenRunAsync(() -> { + if (!failed.get() && limbTypes == null) { + synchronized (this) { + this.setGenerated(slim, true); + } + } + + if (stored.get()) { + this.saveCache(); + } + }).handle((unused, throwable) -> { + if (throwable != null) { + throwable.printStackTrace(); + } + + return null; + }); + } + } + } + } + + public boolean hasSkinUrl(String limbId, boolean slim) { + synchronized (this) { + return this.getMap(slim).containsKey(limbId); + } + } + + public CompletableFuture getSkinUrl(String limbId, boolean slim) { + synchronized (this) { + String url = this.getMap(slim).get(limbId); + return url != null ? CompletableFuture.completedFuture(url) : this.requested.computeIfAbsent(key(slim, limbId), s -> new CompletableFuture<>()); + } + } + + public void saveCache() { + ModelEngineAPI api = ModelEngineAPI.getAPI(); + String cacheId = UUID.nameUUIDFromBytes(this.source.getBytes()).toString(); + String header = cacheId.substring(0, 2); + String remain = cacheId.substring(2); + File file = TFile.createFile(api.getDataFolder(), ".data", "userlimbs", header, remain + ".json"); + + try { + try (FileWriter writer = new FileWriter(file)) { + String data; + synchronized (this) { + data = api.getGson().toJson(this); + } + + writer.write(data); + TLogger.log(LogColor.BRIGHT_GREEN + "Limb data generated: " + this.name); + } + } catch (IOException var13) { + throw new RuntimeException(var13); + } + } + + private synchronized boolean isCovered(boolean slim, Collection limbTypes) { + Map map = this.getMap(slim); + + for (String limbId : limbTypes) { + if (!map.containsKey(limbId) && !this.requested.containsKey(key(slim, limbId))) { + return false; + } + } + + return true; + } + + private static String key(boolean slim, String limbId) { + return (slim ? "slim/" : "classic/") + limbId; + } + + private Map getMap(boolean slim) { + return slim ? this.slim : this.classic; + } + + private void setGenerated(boolean slim, boolean flag) { + if (slim) { + this.slimGenerated = flag; + } else { + this.classicGenerated = flag; + } + } + + public boolean isGenerated(boolean slim) { + return slim ? this.slimGenerated : this.classicGenerated; + } + + private static String describe(Throwable throwable) { + Throwable cause = throwable; + + while (cause.getCause() != null && cause.getCause() != cause) { + cause = cause.getCause(); + } + + String message = cause.getMessage(); + return message != null ? message : cause.getClass().getSimpleName(); + } + + public UserLimbCache(String name, String source) { + this.name = name; + this.source = source; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/limb/UserLimbRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/model/limb/UserLimbRegistry.java new file mode 100644 index 0000000..0c43e90 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/limb/UserLimbRegistry.java @@ -0,0 +1,224 @@ +package com.ticxo.modelengine.api.model.limb; + +import com.destroystokyo.paper.profile.PlayerProfile; +import com.google.gson.Gson; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.utils.MiscUtils; +import com.ticxo.modelengine.api.utils.MojangAPI; +import com.ticxo.modelengine.api.utils.TFile; +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 com.ticxo.modelengine.api.utils.registry.TUnaryRegistry; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import javax.imageio.ImageIO; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import org.bukkit.profile.PlayerTextures.SkinModel; + +public class UserLimbRegistry extends TUnaryRegistry { + private final Map keyedSources = new HashMap<>(); + private final File skinDir; + + public UserLimbRegistry(ModelEngineAPI plugin) { + this.skinDir = TFile.createDirectory(plugin.getDataFolder(), "skins"); + } + + public void generateDefaults() { + ConfigProperty skins = ConfigProperty.DEFAULT_SKINS; + ConfigurationSection section = skins.getSection(); + + for (String key : section.getKeys(false)) { + ConfigurationSection data = section.getConfigurationSection(key); + if (data != null) { + TLogger.log(LogColor.CYAN + "Loading default skin: " + key); + CompletableFuture base64 = this.getImageData(data); + if (base64 == null) { + TLogger.warn("Failed to eager load " + key + ": Missing data value."); + } else { + boolean slim = data.getBoolean("slim", false); + base64.handle((s, throwable) -> { + if (throwable != null) { + throwable.printStackTrace(); + } else { + this.keyedSources.put(key, s); + this.generate(key, s, slim); + TLogger.log(LogColor.BRIGHT_GREEN + "Registered default skin: " + key); + } + + return null; + }); + } + } + } + } + + private CompletableFuture getImageData(ConfigurationSection section) { + for (String key : section.getKeys(false)) { + switch (key) { + case "base64": + return CompletableFuture.supplyAsync(() -> section.getString(key)); + case "url": + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(section.getString(key))) + .timeout(Duration.of(30L, ChronoUnit.SECONDS)) + .GET() + .build(); + HttpClient client = HttpClient.newHttpClient(); + return client.sendAsync(request, BodyHandlers.ofByteArray()) + .thenApply(HttpResponse::body) + .thenApply(bytes -> Base64.getEncoder().encodeToString(bytes)); + case "path": + File imgFile = TFile.createFile(this.skinDir, section.getString(key)); + if (imgFile.exists()) { + return CompletableFuture.supplyAsync(() -> { + try { + return ImageIO.read(imgFile); + } catch (IOException var2) { + throw new RuntimeException(var2); + } + }).thenApply(image -> { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + + try { + ImageIO.write(image, "png", buffer); + return buffer; + } catch (IOException var3x) { + throw new RuntimeException(var3x); + } + }).thenApply(stream -> Base64.getEncoder().encodeToString(stream.toByteArray())); + } + break; + case "username": + String name = section.getString(key); + return CompletableFuture.supplyAsync(() -> MojangAPI.getUUIDFromUsername(name)) + .thenApply(MojangAPI::fromUUID) + .thenCompose(MojangAPI::getRawSkinData); + case "uuid": + UUID uuid = UUID.fromString(section.getString(key)); + return CompletableFuture.supplyAsync(() -> MojangAPI.fromUUID(uuid)).thenCompose(MojangAPI::getRawSkinData); + } + } + + return null; + } + + public boolean tryLoad(String cacheId) { + if (this.registry.containsKey(cacheId)) { + return true; + } else { + ModelEngineAPI api = ModelEngineAPI.getAPI(); + Gson gson = api.getGson(); + String header = cacheId.substring(0, 2); + String remain = cacheId.substring(2); + File file = TFile.createFile(api.getDataFolder(), ".data", "userlimbs", header, remain + ".json"); + if (!file.exists()) { + return false; + } else { + try { + UserLimbCache cache = (UserLimbCache)gson.fromJson(new FileReader(file), UserLimbCache.class); + cache.initialize(); + this.register(cacheId, cache); + return true; + } catch (Exception var8) { + var8.printStackTrace(); + return false; + } + } + } + } + + public void generate(Player player) { + PlayerProfile playerProfile = player.getPlayerProfile(); + boolean slim = playerProfile.getTextures().getSkinModel() == SkinModel.SLIM; + MojangAPI.getRawSkinData(playerProfile).thenAccept(base64 -> this.generate(base64, slim)).handle(MiscUtils::handle); + } + + public void generate(byte[] data, boolean slim) { + this.generate(Base64.getEncoder().encodeToString(data), slim); + } + + public UserLimbCache generate(String base64, boolean slim) { + return this.generate(UUID.nameUUIDFromBytes(base64.getBytes()).toString(), base64, slim); + } + + public UserLimbCache generate(String name, String base64, boolean slim) { + synchronized (this.registry) { + UserLimbCache cache = this.getOrCreate(name, base64); + cache.generate(ModelEngineAPI.getSkinGeneratorService(), slim, this.getUsedLimbTypes()); + return cache; + } + } + + public CompletableFuture getSkinUrlFromKey(String key, String limbType, boolean slim) { + String src = this.keyedSources.get(key); + return src == null + ? CompletableFuture.failedFuture(new RuntimeException("Unknown limb source with key: " + key)) + : this.getSkinUrlFromSource(src, limbType, slim); + } + + public CompletableFuture getSkinUrlFromSource(String source, String limbType, boolean slim) { + synchronized (this.registry) { + String cacheId = UUID.nameUUIDFromBytes(source.getBytes()).toString(); + UserLimbCache cache = this.getOrCreate(cacheId, source); + cache.generate(ModelEngineAPI.getSkinGeneratorService(), slim, Collections.singletonList(limbType)); + return cache.getSkinUrl(limbType, slim); + } + } + + private UserLimbCache getOrCreate(String name, String source) { + String cacheId = UUID.nameUUIDFromBytes(source.getBytes()).toString(); + if (!this.tryLoad(cacheId)) { + this.register(cacheId, new UserLimbCache(name, source)); + } + + return this.get(cacheId); + } + + private Set getUsedLimbTypes() { + BoneBehaviorType type = BoneBehaviorTypes.USER_LIMB; + if (type == null) { + return Set.of(); + } else { + String behaviorId = type.getId(); + HashSet limbTypes = new HashSet<>(); + + for (ModelBlueprint blueprint : ModelEngineAPI.getAPI().getModelRegistry().getValues()) { + Map flatMap = blueprint.getFlatMap(); + if (flatMap != null) { + for (BlueprintBone bone : flatMap.values()) { + Map behavior = bone.getBehaviors().get(behaviorId); + if (behavior != null && behavior.get("type") instanceof String limbType) { + limbTypes.add(limbType); + } + } + } + } + + return limbTypes; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/operation/ModelOperation.java b/api/src/main/java/com/ticxo/modelengine/api/model/operation/ModelOperation.java new file mode 100644 index 0000000..b2bda07 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/operation/ModelOperation.java @@ -0,0 +1,563 @@ +package com.ticxo.modelengine.api.model.operation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +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.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import java.util.function.Consumer; +import java.util.function.Predicate; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +public class ModelOperation { + protected final Entity bukkitEntity; + protected final BaseEntity baseEntity; + protected final String modelId; + protected final boolean overrideHitbox; + protected final boolean baseInvisible; + protected final Boolean renderFire; + protected final Boolean forceFire; + protected final boolean doDamageTint; + protected final String nametagBone; + protected final boolean drivable; + protected final boolean rideable; + protected final boolean lockPitch; + protected final boolean lockYaw; + protected final Double stepHeight; + protected final Integer viewRadius; + protected final float viewRange; + protected final double scale; + protected final Double hitboxScale; + protected final boolean useStateMachine; + protected final boolean invisibleUpdate; + protected final boolean initializeRenderer; + protected final boolean showHitbox; + protected final boolean showShadow; + protected final boolean syncBodyYaw; + protected final boolean shouldSave; + protected final String rootBone; + protected final Consumer postModeledEntityInit; + protected final Consumer postActiveModelInit; + protected final boolean useBaseAsPivot; + protected final boolean cameraPivot; + protected final PivotOverride pivotOverride; + protected final boolean viewSelf; + protected final Predicate playerPredicate; + + protected BaseEntity getBaseEntity() { + if (this.baseEntity != null) { + return this.baseEntity; + } else if (this.bukkitEntity != null) { + return new BukkitEntity(this.bukkitEntity); + } else { + throw new RuntimeException("You must supply a base entity for this operation."); + } + } + + protected boolean isDisguise() { + return this.bukkitEntity instanceof Player || this.baseEntity instanceof BukkitPlayer; + } + + protected ModeledEntity getOrCreateModeledEntity() { + if (this.baseEntity != null) { + return ModelEngineAPI.getOrCreateModeledEntity(this.baseEntity.getUUID(), () -> this.baseEntity); + } else if (this.bukkitEntity != null) { + return ModelEngineAPI.getOrCreateModeledEntity(this.bukkitEntity); + } else { + throw new RuntimeException("You must supply a base entity for this operation."); + } + } + + private static boolean $default$overrideHitbox() { + return true; + } + + private static float $default$viewRange() { + return 4096.0F; + } + + private static double $default$scale() { + return 1.0; + } + + private static boolean $default$initializeRenderer() { + return true; + } + + private static boolean $default$showHitbox() { + return true; + } + + private static boolean $default$showShadow() { + return true; + } + + private static boolean $default$syncBodyYaw() { + return true; + } + + private static boolean $default$shouldSave() { + return true; + } + + private static boolean $default$viewSelf() { + return true; + } + + ModelOperation( + Entity bukkitEntity, + BaseEntity baseEntity, + String modelId, + boolean overrideHitbox, + boolean baseInvisible, + Boolean renderFire, + Boolean forceFire, + boolean doDamageTint, + String nametagBone, + boolean drivable, + boolean rideable, + boolean lockPitch, + boolean lockYaw, + Double stepHeight, + Integer viewRadius, + float viewRange, + double scale, + Double hitboxScale, + boolean useStateMachine, + boolean invisibleUpdate, + boolean initializeRenderer, + boolean showHitbox, + boolean showShadow, + boolean syncBodyYaw, + boolean shouldSave, + String rootBone, + Consumer postModeledEntityInit, + Consumer postActiveModelInit, + boolean useBaseAsPivot, + boolean cameraPivot, + PivotOverride pivotOverride, + boolean viewSelf, + Predicate playerPredicate + ) { + this.bukkitEntity = bukkitEntity; + this.baseEntity = baseEntity; + this.modelId = modelId; + this.overrideHitbox = overrideHitbox; + this.baseInvisible = baseInvisible; + this.renderFire = renderFire; + this.forceFire = forceFire; + this.doDamageTint = doDamageTint; + this.nametagBone = nametagBone; + this.drivable = drivable; + this.rideable = rideable; + this.lockPitch = lockPitch; + this.lockYaw = lockYaw; + this.stepHeight = stepHeight; + this.viewRadius = viewRadius; + this.viewRange = viewRange; + this.scale = scale; + this.hitboxScale = hitboxScale; + this.useStateMachine = useStateMachine; + this.invisibleUpdate = invisibleUpdate; + this.initializeRenderer = initializeRenderer; + this.showHitbox = showHitbox; + this.showShadow = showShadow; + this.syncBodyYaw = syncBodyYaw; + this.shouldSave = shouldSave; + this.rootBone = rootBone; + this.postModeledEntityInit = postModeledEntityInit; + this.postActiveModelInit = postActiveModelInit; + this.useBaseAsPivot = useBaseAsPivot; + this.cameraPivot = cameraPivot; + this.pivotOverride = pivotOverride; + this.viewSelf = viewSelf; + this.playerPredicate = playerPredicate; + } + + public static ModelOperation.Builder builder() { + return new ModelOperation.Builder(); + } + + public static class Builder { + private Entity bukkitEntity; + private BaseEntity baseEntity; + private String modelId; + private boolean overrideHitbox$set; + private boolean overrideHitbox$value; + private boolean baseInvisible; + private Boolean renderFire; + private Boolean forceFire; + private boolean doDamageTint; + private String nametagBone; + private boolean drivable; + private boolean rideable; + private boolean lockPitch; + private boolean lockYaw; + private Double stepHeight; + private Integer viewRadius; + private boolean viewRange$set; + private float viewRange$value; + private boolean scale$set; + private double scale$value; + private Double hitboxScale; + private boolean useStateMachine; + private boolean invisibleUpdate; + private boolean initializeRenderer$set; + private boolean initializeRenderer$value; + private boolean showHitbox$set; + private boolean showHitbox$value; + private boolean showShadow$set; + private boolean showShadow$value; + private boolean syncBodyYaw$set; + private boolean syncBodyYaw$value; + private boolean shouldSave$set; + private boolean shouldSave$value; + private String rootBone; + private Consumer postModeledEntityInit; + private Consumer postActiveModelInit; + private boolean useBaseAsPivot; + private boolean cameraPivot; + private PivotOverride pivotOverride; + private boolean viewSelf$set; + private boolean viewSelf$value; + private Predicate playerPredicate; + + public OperationResult operate(OperationType type) { + return type.process(this.build()); + } + + Builder() { + } + + public ModelOperation.Builder bukkitEntity(Entity bukkitEntity) { + this.bukkitEntity = bukkitEntity; + return this; + } + + public ModelOperation.Builder baseEntity(BaseEntity baseEntity) { + this.baseEntity = baseEntity; + return this; + } + + public ModelOperation.Builder modelId(String modelId) { + this.modelId = modelId; + return this; + } + + public ModelOperation.Builder overrideHitbox(boolean overrideHitbox) { + this.overrideHitbox$value = overrideHitbox; + this.overrideHitbox$set = true; + return this; + } + + public ModelOperation.Builder baseInvisible(boolean baseInvisible) { + this.baseInvisible = baseInvisible; + return this; + } + + public ModelOperation.Builder renderFire(Boolean renderFire) { + this.renderFire = renderFire; + return this; + } + + public ModelOperation.Builder forceFire(Boolean forceFire) { + this.forceFire = forceFire; + return this; + } + + public ModelOperation.Builder doDamageTint(boolean doDamageTint) { + this.doDamageTint = doDamageTint; + return this; + } + + public ModelOperation.Builder nametagBone(String nametagBone) { + this.nametagBone = nametagBone; + return this; + } + + public ModelOperation.Builder drivable(boolean drivable) { + this.drivable = drivable; + return this; + } + + public ModelOperation.Builder rideable(boolean rideable) { + this.rideable = rideable; + return this; + } + + public ModelOperation.Builder lockPitch(boolean lockPitch) { + this.lockPitch = lockPitch; + return this; + } + + public ModelOperation.Builder lockYaw(boolean lockYaw) { + this.lockYaw = lockYaw; + return this; + } + + public ModelOperation.Builder stepHeight(Double stepHeight) { + this.stepHeight = stepHeight; + return this; + } + + public ModelOperation.Builder viewRadius(Integer viewRadius) { + this.viewRadius = viewRadius; + return this; + } + + public ModelOperation.Builder viewRange(float viewRange) { + this.viewRange$value = viewRange; + this.viewRange$set = true; + return this; + } + + public ModelOperation.Builder scale(double scale) { + this.scale$value = scale; + this.scale$set = true; + return this; + } + + public ModelOperation.Builder hitboxScale(Double hitboxScale) { + this.hitboxScale = hitboxScale; + return this; + } + + public ModelOperation.Builder useStateMachine(boolean useStateMachine) { + this.useStateMachine = useStateMachine; + return this; + } + + public ModelOperation.Builder invisibleUpdate(boolean invisibleUpdate) { + this.invisibleUpdate = invisibleUpdate; + return this; + } + + public ModelOperation.Builder initializeRenderer(boolean initializeRenderer) { + this.initializeRenderer$value = initializeRenderer; + this.initializeRenderer$set = true; + return this; + } + + public ModelOperation.Builder showHitbox(boolean showHitbox) { + this.showHitbox$value = showHitbox; + this.showHitbox$set = true; + return this; + } + + public ModelOperation.Builder showShadow(boolean showShadow) { + this.showShadow$value = showShadow; + this.showShadow$set = true; + return this; + } + + public ModelOperation.Builder syncBodyYaw(boolean syncBodyYaw) { + this.syncBodyYaw$value = syncBodyYaw; + this.syncBodyYaw$set = true; + return this; + } + + public ModelOperation.Builder shouldSave(boolean shouldSave) { + this.shouldSave$value = shouldSave; + this.shouldSave$set = true; + return this; + } + + public ModelOperation.Builder rootBone(String rootBone) { + this.rootBone = rootBone; + return this; + } + + public ModelOperation.Builder postModeledEntityInit(Consumer postModeledEntityInit) { + this.postModeledEntityInit = postModeledEntityInit; + return this; + } + + public ModelOperation.Builder postActiveModelInit(Consumer postActiveModelInit) { + this.postActiveModelInit = postActiveModelInit; + return this; + } + + public ModelOperation.Builder useBaseAsPivot(boolean useBaseAsPivot) { + this.useBaseAsPivot = useBaseAsPivot; + return this; + } + + public ModelOperation.Builder cameraPivot(boolean cameraPivot) { + this.cameraPivot = cameraPivot; + return this; + } + + public ModelOperation.Builder pivotOverride(PivotOverride pivotOverride) { + this.pivotOverride = pivotOverride; + return this; + } + + public ModelOperation.Builder viewSelf(boolean viewSelf) { + this.viewSelf$value = viewSelf; + this.viewSelf$set = true; + return this; + } + + public ModelOperation.Builder playerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + return this; + } + + public ModelOperation build() { + boolean overrideHitbox$value = this.overrideHitbox$value; + if (!this.overrideHitbox$set) { + overrideHitbox$value = ModelOperation.$default$overrideHitbox(); + } + + float viewRange$value = this.viewRange$value; + if (!this.viewRange$set) { + viewRange$value = ModelOperation.$default$viewRange(); + } + + double scale$value = this.scale$value; + if (!this.scale$set) { + scale$value = ModelOperation.$default$scale(); + } + + boolean initializeRenderer$value = this.initializeRenderer$value; + if (!this.initializeRenderer$set) { + initializeRenderer$value = ModelOperation.$default$initializeRenderer(); + } + + boolean showHitbox$value = this.showHitbox$value; + if (!this.showHitbox$set) { + showHitbox$value = ModelOperation.$default$showHitbox(); + } + + boolean showShadow$value = this.showShadow$value; + if (!this.showShadow$set) { + showShadow$value = ModelOperation.$default$showShadow(); + } + + boolean syncBodyYaw$value = this.syncBodyYaw$value; + if (!this.syncBodyYaw$set) { + syncBodyYaw$value = ModelOperation.$default$syncBodyYaw(); + } + + boolean shouldSave$value = this.shouldSave$value; + if (!this.shouldSave$set) { + shouldSave$value = ModelOperation.$default$shouldSave(); + } + + boolean viewSelf$value = this.viewSelf$value; + if (!this.viewSelf$set) { + viewSelf$value = ModelOperation.$default$viewSelf(); + } + + return new ModelOperation( + this.bukkitEntity, + this.baseEntity, + this.modelId, + overrideHitbox$value, + this.baseInvisible, + this.renderFire, + this.forceFire, + this.doDamageTint, + this.nametagBone, + this.drivable, + this.rideable, + this.lockPitch, + this.lockYaw, + this.stepHeight, + this.viewRadius, + viewRange$value, + scale$value, + this.hitboxScale, + this.useStateMachine, + this.invisibleUpdate, + initializeRenderer$value, + showHitbox$value, + showShadow$value, + syncBodyYaw$value, + shouldSave$value, + this.rootBone, + this.postModeledEntityInit, + this.postActiveModelInit, + this.useBaseAsPivot, + this.cameraPivot, + this.pivotOverride, + viewSelf$value, + this.playerPredicate + ); + } + + @Override + public String toString() { + return "ModelOperation.Builder(bukkitEntity=" + + this.bukkitEntity + + ", baseEntity=" + + this.baseEntity + + ", modelId=" + + this.modelId + + ", overrideHitbox$value=" + + this.overrideHitbox$value + + ", baseInvisible=" + + this.baseInvisible + + ", renderFire=" + + this.renderFire + + ", forceFire=" + + this.forceFire + + ", doDamageTint=" + + this.doDamageTint + + ", nametagBone=" + + this.nametagBone + + ", drivable=" + + this.drivable + + ", rideable=" + + this.rideable + + ", lockPitch=" + + this.lockPitch + + ", lockYaw=" + + this.lockYaw + + ", stepHeight=" + + this.stepHeight + + ", viewRadius=" + + this.viewRadius + + ", viewRange$value=" + + this.viewRange$value + + ", scale$value=" + + this.scale$value + + ", hitboxScale=" + + this.hitboxScale + + ", useStateMachine=" + + this.useStateMachine + + ", invisibleUpdate=" + + this.invisibleUpdate + + ", initializeRenderer$value=" + + this.initializeRenderer$value + + ", showHitbox$value=" + + this.showHitbox$value + + ", showShadow$value=" + + this.showShadow$value + + ", syncBodyYaw$value=" + + this.syncBodyYaw$value + + ", shouldSave$value=" + + this.shouldSave$value + + ", rootBone=" + + this.rootBone + + ", postModeledEntityInit=" + + this.postModeledEntityInit + + ", postActiveModelInit=" + + this.postActiveModelInit + + ", useBaseAsPivot=" + + this.useBaseAsPivot + + ", cameraPivot=" + + this.cameraPivot + + ", pivotOverride=" + + this.pivotOverride + + ", viewSelf$value=" + + this.viewSelf$value + + ", playerPredicate=" + + this.playerPredicate + + ")"; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/operation/OperationResult.java b/api/src/main/java/com/ticxo/modelengine/api/model/operation/OperationResult.java new file mode 100644 index 0000000..818e7ed --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/operation/OperationResult.java @@ -0,0 +1,11 @@ +package com.ticxo.modelengine.api.model.operation; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; + +public record OperationResult(BaseEntity baseEntity, ModeledEntity modeledEntity, ActiveModel model, Throwable exception) { + public boolean isSuccessful() { + return this.exception == null; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/operation/OperationType.java b/api/src/main/java/com/ticxo/modelengine/api/model/operation/OperationType.java new file mode 100644 index 0000000..b73038f --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/operation/OperationType.java @@ -0,0 +1,137 @@ +package com.ticxo.modelengine.api.model.operation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.NameTag; +import java.util.function.Function; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.apache.commons.lang3.NotImplementedException; +import org.bukkit.entity.Entity; + +public enum OperationType { + ADD_MODEL( + operation -> { + ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(operation.modelId); + if (blueprint == null) { + return new OperationResult(operation.getBaseEntity(), null, null, new RuntimeException("Unknown blueprint: " + operation.modelId)); + } else { + boolean disguise = operation.isDisguise(); + ModeledEntity model = operation.getOrCreateModeledEntity(); + if (model.isInitialized() && model.getModel(operation.modelId).isPresent()) { + return new OperationResult(operation.getBaseEntity(), null, null, new RuntimeException("Base entity already has model: " + operation.modelId)); + } else { + model.restore(); + BaseEntity base = model.getBase(); + double hitboxScale = operation.hitboxScale == null ? operation.scale : operation.hitboxScale; + if (model.getModel(operation.modelId).isPresent()) { + return new OperationResult(base, model, null, new RuntimeException("Base entity already has model: " + operation.modelId)); + } else { + Entity bukkitEntity = base.getOriginal() instanceof Entity entity ? entity : null; + model.setSaved(operation.shouldSave); + if (operation.baseInvisible && bukkitEntity != null) { + ModelEngineAPI.getEntityHandler().setForcedInvisible(bukkitEntity, true); + } + + if (disguise && model.getBase().getData() instanceof BukkitEntityData data) { + if (operation.viewSelf) { + data.getTracked().addForcedPairing(base.getUUID()); + } + + if (operation.playerPredicate != null) { + data.getTracked().setPlayerPredicate(operation.playerPredicate); + data.syncUpdate(); + data.asyncUpdate(); + } + } + + if (operation.stepHeight != null) { + model.getBase().setMaxStepHeight(operation.stepHeight); + } + + if (operation.viewRadius != 0) { + model.getBase().setRenderRadius(Math.max(operation.viewRadius, 0)); + } + + if (operation.syncBodyYaw && bukkitEntity != null) { + model.getBase().getBodyRotationController().setYBodyRot(bukkitEntity.getLocation().getYaw()); + } + + ActiveModel activeModel = ModelEngineAPI.createActiveModel( + blueprint, null, am -> operation.useStateMachine ? ModelEngineAPI.createStateMachineHandler(am) : ModelEngineAPI.createPriorityHandler(am) + ); + activeModel.setScale(operation.scale); + activeModel.setHitboxScale(hitboxScale); + activeModel.setCanHurt(operation.doDamageTint); + activeModel.setLockPitch(operation.lockPitch); + activeModel.setLockYaw(operation.lockYaw); + activeModel.setInvisUpdate(operation.invisibleUpdate); + activeModel.setAutoRendererInitialization(operation.initializeRenderer); + activeModel.setHitboxVisible(operation.showHitbox); + activeModel.setShadowVisible(operation.showShadow); + activeModel.setViewRange(operation.viewRange); + activeModel.setRenderFire(operation.renderFire); + activeModel.setOnFire(operation.forceFire); + activeModel.setCameraPivot(operation.cameraPivot); + if (operation.useBaseAsPivot && bukkitEntity != null) { + activeModel.setPivotOverride(ModelEngineAPI.getPivotOverrideRegistry().getOrCreate(bukkitEntity)); + } else if (operation.pivotOverride != null) { + activeModel.setPivotOverride(operation.pivotOverride); + } + + model.setBaseEntityVisible(!operation.baseInvisible); + model.addModel(activeModel, operation.overrideHitbox).ifPresent(ActiveModel::destroy); + activeModel.getMountManager().ifPresent(mountManager -> { + ((MountManager)mountManager).setCanRide(operation.rideable); + ((MountManager)mountManager).setCanDrive(operation.drivable); + ((MountData)model.getMountData()).setMainMountManager(mountManager); + }); + if (operation.nametagBone != null && bukkitEntity != null) { + activeModel.getBone(operation.nametagBone) + .flatMap(modelBone -> modelBone.getBoneBehavior(BoneBehaviorTypes.NAMETAG)) + .ifPresent(nameTag -> { + ((NameTag)nameTag).setComponentSupplier(() -> { + if (ServerInfo.IS_PAPER) { + Component name = ServerInfo.IS_FOLIA + ? ModelEngineAPI.getEntityHandler().getCustomName(bukkitEntity) + : bukkitEntity.customName(); + return (Component)(name == null ? Component.empty() : name); + } else { + String name = bukkitEntity.getCustomName(); + return name == null ? null : LegacyComponentSerializer.legacyAmpersand().deserialize(name); + } + }); + ((NameTag)nameTag).setVisible(true); + }); + } + + if (operation.rootBone != null) { + activeModel.getBone(operation.rootBone).ifPresent(bone -> model.getRootMotionHandler().setRootBone(bone)); + } + + return new OperationResult(base, model, activeModel, null); + } + } + } + } + ), + REMOVE_MODEL(operation -> new OperationResult(null, null, null, new NotImplementedException("Remove functionality is still work in progress."))); + + private final Function processor; + + public OperationResult process(ModelOperation operation) { + return this.processor.apply(operation); + } + + private OperationType(Function processor) { + this.processor = processor; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayBone.java b/api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayBone.java new file mode 100644 index 0000000..042752c --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayBone.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.api.model.render; + +import com.ticxo.modelengine.api.lod.BoneSnapshotHandler; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.bukkit.entity.Display.Billboard; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.bukkit.inventory.ItemStack; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public interface DisplayBone { + default boolean isDirty() { + return this.isTransformDirty() || this.isRenderDirty() || this.isModelDirty(); + } + + default boolean isSkippable() { + return this.isTransformDirty() && !this.isRenderDirty() && !this.isModelDirty(); + } + + default boolean isTransformDirty() { + return this.getPosition().isDirty() || this.getLeftRotation().isDirty() || this.getScale().isDirty() || this.getRightRotation().isDirty(); + } + + default boolean isRenderDirty() { + return this.getBillboard().isDirty() + || this.getDisplay().isDirty() + || this.getVisibility().isDirty() + || this.getGlowing().isDirty() + || this.getGlowColor().isDirty() + || this.getBrightness().isDirty() + || this.getStep().isDirty(); + } + + default boolean isModelDirty() { + return this.getModelUpdateScheme().hasUpdate(); + } + + default void clearDirty() { + this.getStep().clearDirty(); + this.getPosition().clearDirty(); + this.getLeftRotation().clearDirty(); + this.getScale().clearDirty(); + this.getRightRotation().clearDirty(); + this.getBillboard().clearDirty(); + this.getModelUpdateScheme().reset(); + this.getDisplay().clearDirty(); + this.getVisibility().clearDirty(); + this.getGlowing().clearDirty(); + this.getGlowColor().clearDirty(); + this.getBrightness().clearDirty(); + } + + default boolean isAudienceGlowDirty() { + return this.getGlowAudience().isDirty() || this.getAudienceGlowing().isDirty() || this.getAudienceGlowColor().isDirty(); + } + + default void clearAudienceGlowDirty() { + this.getGlowAudience().clearDirty(); + this.getAudienceGlowing().clearDirty(); + this.getAudienceGlowColor().clearDirty(); + } + + String getBoneId(); + + BoneSnapshotHandler getSnapshotHandler(); + + DataTracker getRender(); + + DataTracker getStep(); + + DataTracker getPosition(); + + DataTracker getLeftRotation(); + + DataTracker getScale(); + + DataTracker getRightRotation(); + + DataTracker getBillboard(); + + Map getModel(); + + UpdateScheme getModelUpdateScheme(); + + DataTracker getDisplay(); + + DataTracker getVisibility(); + + DataTracker getGlowing(); + + DataTracker getGlowColor(); + + DataTracker getBrightness(); + + DataTracker> getGlowAudience(); + + DataTracker getAudienceGlowing(); + + DataTracker getAudienceGlowColor(); + + public interface BoneData { + int getId(); + + UUID getUuid(); + + DisplayBone getBone(); + + DataTracker getModel(); + + int getModelHash(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayFire.java b/api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayFire.java new file mode 100644 index 0000000..7026d16 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayFire.java @@ -0,0 +1,26 @@ +package com.ticxo.modelengine.api.model.render; + +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.UUID; +import org.bukkit.inventory.ItemStack; +import org.joml.Vector3f; + +public interface DisplayFire { + int getId(); + + UUID getUuid(); + + DataTracker getPosition(); + + DataTracker getScale(); + + DataTracker getFireModel(); + + DataTracker getVisible(); + + void clearDirty(); + + default boolean isDirty() { + return this.getPosition().isDirty() || this.getScale().isDirty() || this.getFireModel().isDirty() || this.getVisible().isDirty(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayRenderer.java b/api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayRenderer.java new file mode 100644 index 0000000..e7aac84 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/render/DisplayRenderer.java @@ -0,0 +1,111 @@ +package com.ticxo.modelengine.api.model.render; + +import com.ticxo.modelengine.api.model.bone.render.renderer.RenderQueues; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.UUID; +import org.joml.Vector3f; + +public interface DisplayRenderer extends ModelRenderer, RenderQueues { + int getTick(); + + DisplayRenderer.Pivot getPivot(); + + DisplayRenderer.Hitbox getHitbox(); + + void pushFullUpdate(UUID var1); + + boolean pollFullUpdate(UUID var1); + + default boolean hasGlowAudience() { + for (DisplayBone bone : this.getRendered().values()) { + if (bone.getGlowAudience().get() != null) { + return true; + } + } + + return false; + } + + public interface Hitbox { + int getPivotId(); + + UUID getPivotUuid(); + + int getHitboxId(); + + UUID getHitboxUuid(); + + int getShadowId(); + + UUID getShadowUuid(); + + void clearDirty(); + + DataTracker getPosition(); + + DataTracker getWidth(); + + DataTracker getHeight(); + + DataTracker getShadowRadius(); + + DataTracker getHitboxVisible(); + + DataTracker getShadowVisible(); + + DataTracker getFireVisible(); + + PooledCollection getFireDisplay(); + + default boolean isHitboxDirty() { + return this.getWidth().isDirty() || this.getHeight().isDirty(); + } + + default boolean isHitboxVisible() { + return this.getHitboxVisible().get(); + } + + default boolean isShadowVisible() { + return this.getShadowVisible().get(); + } + + default boolean isFireVisible() { + return this.getFireVisible().get(); + } + + default boolean isPivotVisible() { + return this.isHitboxVisible() || this.isShadowVisible() || this.isFireVisible(); + } + + default PositionCodec getPositionCodec() { + return null; + } + } + + public interface Pivot { + int getId(); + + UUID getUuid(); + + void clearDirty(); + + boolean isOverridden(); + + DataTracker getPosition(); + + CollectionDataTracker getPassengers(); + + DataTracker getCameraHeight(); + + default boolean isCameraPivot() { + return this.getCameraHeight().get() != null; + } + + default PositionCodec getPositionCodec() { + return null; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/render/ModelRenderer.java b/api/src/main/java/com/ticxo/modelengine/api/model/render/ModelRenderer.java new file mode 100644 index 0000000..b9d28e3 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/render/ModelRenderer.java @@ -0,0 +1,25 @@ +package com.ticxo.modelengine.api.model.render; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.nms.RenderParsers; + +public interface ModelRenderer { + ActiveModel getActiveModel(); + + void updatePivotOverride(PivotOverride var1); + + boolean isInitialized(); + + void initialize(); + + void readModelData(); + + void sendToClient(RenderParsers var1); + + void destroy(RenderParsers var1); + + void createRealEntities(); + + boolean pollFirstSpawn(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/model/render/ModelRendererParser.java b/api/src/main/java/com/ticxo/modelengine/api/model/render/ModelRendererParser.java new file mode 100644 index 0000000..e86b7fd --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/model/render/ModelRendererParser.java @@ -0,0 +1,7 @@ +package com.ticxo.modelengine.api.model.render; + +public interface ModelRendererParser { + void sendToClients(T var1); + + void destroy(T var1); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/mount/MountControllerTypeRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/mount/MountControllerTypeRegistry.java new file mode 100644 index 0000000..6432330 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/mount/MountControllerTypeRegistry.java @@ -0,0 +1,7 @@ +package com.ticxo.modelengine.api.mount; + +import com.ticxo.modelengine.api.mount.controller.MountControllerType; +import com.ticxo.modelengine.api.utils.registry.TUnaryRegistry; + +public class MountControllerTypeRegistry extends TUnaryRegistry { +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/mount/MountPairManager.java b/api/src/main/java/com/ticxo/modelengine/api/mount/MountPairManager.java new file mode 100644 index 0000000..b36b464 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/mount/MountPairManager.java @@ -0,0 +1,95 @@ +package com.ticxo.modelengine.api.mount; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import it.unimi.dsi.fastutil.Pair; +import java.util.Map; +import java.util.UUID; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.jetbrains.annotations.Nullable; + +public class MountPairManager { + private final Map> mountedPair = Maps.newConcurrentMap(); + + public void updatePassengerPosition() { + for (Pair pair : this.mountedPair.values()) { + ActiveModel model = (ActiveModel)pair.left(); + MountController controller = (MountController)pair.right(); + if (model.getModeledEntity() != null) { + BaseEntity base = model.getModeledEntity().getBase(); + MoveController moveController = base.getMoveController(); + Runnable updateTask = () -> { + boolean engineTick; + if (moveController.ticksMountController()) { + engineTick = base.getOriginal() instanceof LivingEntity living && !living.hasAI(); + } else { + engineTick = controller.shouldEngineTickMovement(); + } + + if (engineTick) { + if (controller.getInput() == null) { + controller.setInput(new MountController.MountInput()); + } + + Mount mount = controller.getMount(); + if (mount != null && mount.isDriver()) { + controller.updateDriverMovement(moveController, model); + } else { + controller.updatePassengerMovement(moveController, model); + } + } + + controller.updateRiderPosition(moveController); + }; + if (ServerInfo.IS_FOLIA) { + Entity entity = (Entity)base.getOriginal(); + entity.getScheduler().execute(ModelEngineAPI.getAPI(), updateTask, null, 1L); + } else { + try { + updateTask.run(); + } catch (Throwable var9) { + var9.printStackTrace(); + } + } + } + } + } + + public void registerMountedPair(Entity entity, ActiveModel model, MountController controller) { + this.mountedPair.put(entity.getUniqueId(), Pair.of(model, controller)); + } + + public void unregisterMountedPair(UUID uuid) { + this.mountedPair.remove(uuid); + } + + @Nullable + public Pair get(UUID uuid) { + return this.mountedPair.get(ModelEngineAPI.getAPI().getDisguiseRelayOrDefault(uuid)); + } + + public ActiveModel getMountedPair(UUID uuid) { + Pair pair = this.get(uuid); + return pair == null ? null : (ActiveModel)pair.left(); + } + + public MountController getController(UUID uuid) { + Pair pair = this.get(uuid); + return pair == null ? null : (MountController)pair.right(); + } + + public void tryDismount(Entity entity) { + ActiveModel model = this.getMountedPair(entity.getUniqueId()); + if (model != null) { + model.getMountManager().ifPresent(mountManager -> ((MountManager)mountManager).dismountRider(entity)); + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountController.java b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountController.java new file mode 100644 index 0000000..b7e53b2 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountController.java @@ -0,0 +1,163 @@ +package com.ticxo.modelengine.api.mount.controller; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import org.bukkit.entity.Entity; +import org.joml.Vector3f; + +public interface MountController { + Entity getEntity(); + + MountController.MountInput getInput(); + + void setInput(MountController.MountInput var1); + + Mount getMount(); + + void setCanDamageMount(boolean var1); + + boolean canDamageMount(); + + void setCanInteractMount(boolean var1); + + boolean canInteractMount(); + + void updateDriverMovement(MoveController var1, ActiveModel var2); + + void updatePassengerMovement(MoveController var1, ActiveModel var2); + + default boolean shouldEngineTickMovement() { + return false; + } + + default void updateRiderPosition(MoveController controller) { + Vector3f pos = this.getMount().getGlobalLocation(); + controller.movePassenger(this.getEntity(), pos.x, pos.y, pos.z); + } + + void updateDirection(LookController var1, ActiveModel var2); + + public static class MountInput { + private Float side; + private Float front; + private boolean forward; + private boolean backward; + private boolean left; + private boolean right; + private boolean jump; + private boolean sneak; + private boolean sprint; + private boolean updated; + + public MountInput() { + this(false, false, false, false, false, false, false); + } + + public MountInput(float side, float front, boolean jump, boolean sneak) { + this.side = side; + this.front = front; + this.jump = jump; + this.sneak = sneak; + } + + public MountInput(boolean forward, boolean backward, boolean left, boolean right, boolean jump, boolean sneak, boolean sprint) { + this.forward = forward; + this.backward = backward; + this.left = left; + this.right = right; + this.jump = jump; + this.sneak = sneak; + this.sprint = sprint; + } + + public float getFront() { + if (this.front != null) { + return this.front; + } else { + return this.forward ? 1.0F : (this.backward ? -1.0F : 0.0F); + } + } + + public float getSide() { + if (this.side != null) { + return this.side; + } else { + return this.left ? 1.0F : (this.right ? -1.0F : 0.0F); + } + } + + public boolean isForward() { + return this.forward; + } + + public boolean isBackward() { + return this.backward; + } + + public boolean isLeft() { + return this.left; + } + + public boolean isRight() { + return this.right; + } + + public boolean isJump() { + return this.jump; + } + + public boolean isSneak() { + return this.sneak; + } + + public boolean isSprint() { + return this.sprint; + } + + public boolean isUpdated() { + return this.updated; + } + + public void setSide(Float side) { + this.side = side; + } + + public void setFront(Float front) { + this.front = front; + } + + public void setForward(boolean forward) { + this.forward = forward; + } + + public void setBackward(boolean backward) { + this.backward = backward; + } + + public void setLeft(boolean left) { + this.left = left; + } + + public void setRight(boolean right) { + this.right = right; + } + + public void setJump(boolean jump) { + this.jump = jump; + } + + public void setSneak(boolean sneak) { + this.sneak = sneak; + } + + public void setSprint(boolean sprint) { + this.sprint = sprint; + } + + public void setUpdated(boolean updated) { + this.updated = updated; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerSupplier.java b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerSupplier.java new file mode 100644 index 0000000..e576821 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerSupplier.java @@ -0,0 +1,9 @@ +package com.ticxo.modelengine.api.mount.controller; + +import com.ticxo.modelengine.api.model.bone.type.Mount; +import org.bukkit.entity.Entity; + +@FunctionalInterface +public interface MountControllerSupplier { + MountController createController(Entity var1, Mount var2); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerType.java b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerType.java new file mode 100644 index 0000000..00857bb --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerType.java @@ -0,0 +1,18 @@ +package com.ticxo.modelengine.api.mount.controller; + +import com.ticxo.modelengine.api.model.bone.type.Mount; +import java.util.function.BiFunction; +import org.bukkit.entity.Entity; + +public class MountControllerType implements MountControllerSupplier { + private final BiFunction controllerConstructor; + + @Override + public MountController createController(Entity entity, Mount mount) { + return this.controllerConstructor.apply(entity, mount); + } + + public MountControllerType(BiFunction controllerConstructor) { + this.controllerConstructor = controllerConstructor; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerTypes.java b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerTypes.java new file mode 100644 index 0000000..8568b2a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/MountControllerTypes.java @@ -0,0 +1,11 @@ +package com.ticxo.modelengine.api.mount.controller; + +import com.ticxo.modelengine.api.mount.controller.impl.FlyingMountController; +import com.ticxo.modelengine.api.mount.controller.impl.WalkingMountController; + +public class MountControllerTypes { + public static final MountControllerType WALKING = new MountControllerType((entity, mount) -> new WalkingMountController(entity, mount, false)); + public static final MountControllerType WALKING_FORCE = new MountControllerType((entity, mount) -> new WalkingMountController(entity, mount, true)); + public static final MountControllerType FLYING = new MountControllerType((entity, mount) -> new FlyingMountController(entity, mount, false)); + public static final MountControllerType FLYING_FORCE = new MountControllerType((entity, mount) -> new FlyingMountController(entity, mount, true)); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/AbstractMountController.java b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/AbstractMountController.java new file mode 100644 index 0000000..66f8cde --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/AbstractMountController.java @@ -0,0 +1,76 @@ +package com.ticxo.modelengine.api.mount.controller.impl; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import org.bukkit.Location; +import org.bukkit.entity.Entity; + +public abstract class AbstractMountController implements MountController { + protected final Entity entity; + protected final Mount mount; + protected MountController.MountInput input; + protected boolean canDamageMount; + protected boolean canInteractMount; + + @Override + public boolean canDamageMount() { + return this.canDamageMount; + } + + @Override + public boolean canInteractMount() { + return this.canInteractMount; + } + + @Override + public void updateDirection(LookController controller, ActiveModel model) { + Location location = this.getEntity().getLocation(); + controller.setHeadYaw(location.getYaw()); + controller.setPitch(location.getPitch() * 0.5F); + } + + public AbstractMountController(Entity entity, Mount mount) { + this.entity = entity; + this.mount = mount; + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Mount getMount() { + return this.mount; + } + + @Override + public MountController.MountInput getInput() { + return this.input; + } + + public boolean isCanDamageMount() { + return this.canDamageMount; + } + + public boolean isCanInteractMount() { + return this.canInteractMount; + } + + @Override + public void setInput(MountController.MountInput input) { + this.input = input; + } + + @Override + public void setCanDamageMount(boolean canDamageMount) { + this.canDamageMount = canDamageMount; + } + + @Override + public void setCanInteractMount(boolean canInteractMount) { + this.canInteractMount = canInteractMount; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/FlyingMountController.java b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/FlyingMountController.java new file mode 100644 index 0000000..fb6bff9 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/FlyingMountController.java @@ -0,0 +1,56 @@ +package com.ticxo.modelengine.api.mount.controller.impl; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import java.util.Optional; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; + +public class FlyingMountController extends AbstractMountController { + private final boolean force; + + public FlyingMountController(Entity entity, Mount mount, boolean force) { + super(entity, mount); + this.force = force; + } + + @Override + public void updateDriverMovement(MoveController controller, ActiveModel model) { + Optional maybeMount = model.getMountManager(); + if (!maybeMount.isEmpty()) { + BehaviorManager manager = (BehaviorManager)maybeMount.get(); + controller.nullifyFallDistance(); + Vector original = controller.getVelocity(); + controller.setVelocity(original.getX(), 0.0, original.getZ()); + if (this.input.isSneak()) { + if (!controller.isOnGround()) { + controller.addVelocity(0.0, -controller.getSpeed(), 0.0); + } else if (!this.force) { + ((MountManager)manager).dismountDriver(); + controller.move(0.0F, 0.0F, 0.0F, 0.0F); + return; + } + } + + if (this.input.isJump()) { + controller.addVelocity(0.0, controller.getSpeed(), 0.0); + } + + controller.move(this.input.getSide(), 0.0F, this.input.getFront(), 1.0F); + } + } + + @Override + public void updatePassengerMovement(MoveController controller, ActiveModel model) { + Optional maybeMount = model.getMountManager(); + if (!maybeMount.isEmpty()) { + BehaviorManager manager = (BehaviorManager)maybeMount.get(); + if (!this.force && this.input.isSneak()) { + ((MountManager)manager).dismountRider(this.entity); + } + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/WalkingMountController.java b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/WalkingMountController.java new file mode 100644 index 0000000..5e8138a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/mount/controller/impl/WalkingMountController.java @@ -0,0 +1,46 @@ +package com.ticxo.modelengine.api.mount.controller.impl; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import java.util.Optional; +import org.bukkit.entity.Entity; + +public class WalkingMountController extends AbstractMountController { + private final boolean force; + + public WalkingMountController(Entity entity, Mount mount, boolean force) { + super(entity, mount); + this.force = force; + } + + @Override + public void updateDriverMovement(MoveController controller, ActiveModel model) { + Optional maybeMount = model.getMountManager(); + if (!maybeMount.isEmpty()) { + BehaviorManager manager = (BehaviorManager)maybeMount.get(); + if (!this.force && this.input.isSneak()) { + ((MountManager)manager).dismountDriver(); + controller.move(0.0F, 0.0F, 0.0F, 0.0F); + } else { + controller.move(this.input.getSide(), 0.0F, this.input.getFront(), 1.0F); + if (this.input.isJump() && (controller.isOnGround() || controller.isInWater())) { + controller.jump(); + } + } + } + } + + @Override + public void updatePassengerMovement(MoveController controller, ActiveModel model) { + Optional maybeMount = model.getMountManager(); + if (!maybeMount.isEmpty()) { + BehaviorManager manager = (BehaviorManager)maybeMount.get(); + if (!this.force && this.input.isSneak()) { + ((MountManager)manager).dismountRider(this.entity); + } + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/NMSHandler.java b/api/src/main/java/com/ticxo/modelengine/api/nms/NMSHandler.java new file mode 100644 index 0000000..a267fcc --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/NMSHandler.java @@ -0,0 +1,76 @@ +package com.ticxo.modelengine.api.nms; + +import com.ticxo.modelengine.api.generator.BaseItemEnum; +import com.ticxo.modelengine.api.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.ui.AnvilHandler; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import java.util.Collection; +import java.util.Locale; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.bukkit.Color; +import org.bukkit.NamespacedKey; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.util.Transformation; +import org.joml.Matrix4f; + +public interface NMSHandler { + EntityHandler getEntityHandler(); + + NetworkHandler getNetworkHandler(); + + default AnvilHandler getAnvilHandler() { + return null; + } + + RenderParsers getGlobalParsers(); + + RenderParsers createParsers(); + + void sendPivotOverrides(); + + default Set createStack(ItemModelData data, ItemModelData.Context context) { + Collection subModels = data.getMultiModels().getSubModels(); + return subModels.stream().map(subModel -> subModel.getItem().create(context.color(), subModel.getData())).collect(Collectors.toSet()); + } + + default boolean colorStack(ItemStack stack, Color color) { + BaseItemEnum base = BaseItemEnum.fromMaterial(stack.getType()); + if (base == null) { + return false; + } else { + ItemMeta meta = stack.getItemMeta(); + base.color(meta, color); + stack.setItemMeta(meta); + return true; + } + } + + default NamespacedKey getPlayerHeadModelKey() { + return new NamespacedKey(ConfigProperty.NAMESPACE.getString().toLowerCase(Locale.ENGLISH), "player_head"); + } + + default void applyPlayerHeadItemModel(ItemStack stack) { + } + + ModelRendererParser getModelRendererParser(T var1); + + BehaviorRendererParser getBehaviorRendererParser(T var1); + + VFXRendererParser getVFXRendererParser(T var1); + + Transformation decompose(Matrix4f var1); + + default void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/RenderParsers.java b/api/src/main/java/com/ticxo/modelengine/api/nms/RenderParsers.java new file mode 100644 index 0000000..a1efaea --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/RenderParsers.java @@ -0,0 +1,44 @@ +package com.ticxo.modelengine.api.nms; + +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.Predicate; +import java.util.function.Supplier; + +public class RenderParsers { + private final Map, Supplier>> modelParsers = new HashMap<>(); + private final Map, Supplier>> behaviorParsers = new HashMap<>(); + + public void registerModelParser(Predicate predicate, Supplier> parser) { + this.modelParsers.put(predicate, parser); + } + + public void registerBehaviorParser(Predicate predicate, Supplier> parser) { + this.behaviorParsers.put(predicate, parser); + } + + public ModelRendererParser getModelParser(T renderer) { + for (Entry, Supplier>> entry : this.modelParsers.entrySet()) { + if (((Predicate)entry.getKey()).test(renderer)) { + return (ModelRendererParser)entry.getValue().get(); + } + } + + return null; + } + + public BehaviorRendererParser getBehaviorParser(T renderer) { + for (Entry, Supplier>> entry : this.behaviorParsers.entrySet()) { + if (((Predicate)entry.getKey()).test(renderer)) { + return (BehaviorRendererParser)entry.getValue().get(); + } + } + + return null; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/entity/AttributeAccessor.java b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/AttributeAccessor.java new file mode 100644 index 0000000..7e5dac4 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/AttributeAccessor.java @@ -0,0 +1,5 @@ +package com.ticxo.modelengine.api.nms.entity; + +public interface AttributeAccessor { + float getMaxHealth(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/entity/EntityHandler.java b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/EntityHandler.java new file mode 100644 index 0000000..ea8c609 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/EntityHandler.java @@ -0,0 +1,371 @@ +package com.ticxo.modelengine.api.nms.entity; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +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.entity.wrapper.TrackedEntity; +import java.util.EnumSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Supplier; +import net.kyori.adventure.text.Component; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.BoundingBox; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public interface EntityHandler { + int ON_MIN_X = 1; + int ON_MAX_X = 2; + int ON_MIN_Y = 4; + int ON_MAX_Y = 8; + int ON_MIN_Z = 16; + int ON_MAX_Z = 32; + + static Set getPoints(byte face) { + EnumSet set = EnumSet.noneOf(EntityHandler.Point.class); + if ((face & 1) == 1) { + set.add(EntityHandler.Point.CORNER_A); + set.add(EntityHandler.Point.CORNER_E); + set.add(EntityHandler.Point.CORNER_C); + set.add(EntityHandler.Point.CORNER_G); + } + + if ((face & 4) == 4) { + set.add(EntityHandler.Point.CORNER_A); + set.add(EntityHandler.Point.CORNER_E); + set.add(EntityHandler.Point.CORNER_B); + set.add(EntityHandler.Point.CORNER_F); + } + + if ((face & 16) == 16) { + set.add(EntityHandler.Point.CORNER_A); + set.add(EntityHandler.Point.CORNER_C); + set.add(EntityHandler.Point.CORNER_B); + set.add(EntityHandler.Point.CORNER_D); + } + + if ((face & 2) == 2) { + set.add(EntityHandler.Point.CORNER_B); + set.add(EntityHandler.Point.CORNER_F); + set.add(EntityHandler.Point.CORNER_D); + set.add(EntityHandler.Point.CORNER_H); + } + + if ((face & 8) == 8) { + set.add(EntityHandler.Point.CORNER_C); + set.add(EntityHandler.Point.CORNER_G); + set.add(EntityHandler.Point.CORNER_D); + set.add(EntityHandler.Point.CORNER_H); + } + + if ((face & 32) == 32) { + set.add(EntityHandler.Point.CORNER_E); + set.add(EntityHandler.Point.CORNER_G); + set.add(EntityHandler.Point.CORNER_F); + set.add(EntityHandler.Point.CORNER_H); + } + + return set; + } + + static boolean sweepCullPoints( + int minX, + int minY, + int minZ, + int maxX, + int maxY, + int maxZ, + EntityHandler.BoxRelToCam relX, + EntityHandler.BoxRelToCam relY, + EntityHandler.BoxRelToCam relZ, + EntityHandler.CullPointVisitor visitor + ) { + if (minX <= maxX && minY <= maxY && minZ <= maxZ) { + boolean hasX = relX != EntityHandler.BoxRelToCam.INSIDE; + boolean hasY = relY != EntityHandler.BoxRelToCam.INSIDE; + boolean hasZ = relZ != EntityHandler.BoxRelToCam.INSIDE; + int planeX = relX == EntityHandler.BoxRelToCam.POSITIVE ? minX : maxX + 1; + int planeY = relY == EntityHandler.BoxRelToCam.POSITIVE ? minY : maxY + 1; + int planeZ = relZ == EntityHandler.BoxRelToCam.POSITIVE ? minZ : maxZ + 1; + if (hasX) { + for (int y = minY; y <= maxY + 1; y++) { + for (int z = minZ; z <= maxZ + 1; z++) { + if (visitor.visit(planeX, y, z)) { + return true; + } + } + } + } + + if (hasY) { + for (int x = minX; x <= maxX + 1; x++) { + if (!hasX || x != planeX) { + for (int zx = minZ; zx <= maxZ + 1; zx++) { + if (visitor.visit(x, planeY, zx)) { + return true; + } + } + } + } + } + + if (hasZ) { + for (int xx = minX; xx <= maxX + 1; xx++) { + if (!hasX || xx != planeX) { + for (int y = minY; y <= maxY + 1; y++) { + if ((!hasY || y != planeY) && visitor.visit(xx, y, planeZ)) { + return true; + } + } + } + } + } + + return false; + } else { + return false; + } + } + + void updateConfig(); + + int getNextEntityId(); + + void setHitbox(Entity var1, Hitbox var2); + + void setStepHeight(Entity var1, double var2); + + double getStepHeight(Entity var1); + + void setPosition(Entity var1, double var2, double var4, double var6); + + void movePassenger(Entity var1, double var2, double var4, double var6); + + void forceSpawn(BaseEntity var1, Player var2); + + default void forceSpawn(Entity entity) { + TrackedEntity tracked = this.wrapTrackedEntity(entity); + if (tracked != null) { + tracked.broadcastSpawn(); + } + } + + void forceDespawn(BaseEntity var1, Player var2); + + default void forceDespawn(Entity entity) { + TrackedEntity tracked = this.wrapTrackedEntity(entity); + if (tracked != null) { + tracked.broadcastRemove(); + } + } + + void setForcedInvisible(Entity var1, boolean var2); + + default boolean isForcedInvisible(Entity entity) { + return this.isForcedInvisible(entity.getUniqueId()); + } + + boolean isForcedInvisible(UUID var1); + + void clearForcedInvisible(UUID var1); + + BodyRotationController wrapBodyRotationControl(Entity var1, Supplier var2); + + MoveController wrapMoveController(Entity var1, Supplier var2); + + LookController wrapLookController(Entity var1, Supplier var2); + + void wrapNavigation(Entity var1); + + HitboxEntity createHitbox(Location var1, ModelBone var2, SubHitbox var3); + + @Nullable + HitboxEntity castHitbox(Entity var1); + + boolean hurt(Entity var1, Object var2, float var3); + + EntityHandler.InteractionResult interact(Entity var1, HumanEntity var2, EquipmentSlot var3); + + void spawnDynamicHitbox(DynamicHitbox var1); + + void updateDynamicHitbox(DynamicHitbox var1); + + void destroyDynamicHitbox(DynamicHitbox var1); + + void forceUseItem(Player var1, EquipmentSlot var2); + + float getYRot(Entity var1); + + float getYHeadRot(Entity var1); + + float getXHeadRot(Entity var1); + + float getYBodyRot(Entity var1); + + void setYRot(Entity var1, float var2); + + void setYHeadRot(Entity var1, float var2); + + void setXHeadRot(Entity var1, float var2); + + void setYBodyRot(Entity var1, float var2); + + void move(Entity var1, double var2, double var4, double var6); + + boolean isWalking(Entity var1); + + boolean isStrafing(Entity var1); + + boolean isJumping(Entity var1); + + boolean isFlying(Entity var1); + + float getHealth(Entity var1); + + float getMaxHealth(Entity var1); + + default AttributeAccessor createAttributeAccessor(Entity entity) { + return () -> this.getMaxHealth(entity); + } + + default Vector3f getPivotOffset(Entity entity) { + return null; + } + + default Float getCameraPivotHeight(Entity entity) { + return null; + } + + default Float getCameraEyeHeight(Entity entity) { + return null; + } + + boolean isRemoved(Entity var1); + + int getGlowColor(Entity var1); + + void setDeathTick(Entity var1, int var2); + + TrackedEntity wrapTrackedEntity(Entity var1); + + boolean shouldCull(Player var1, Location var2, BoundingBox var3); + + default int getEntityId(Entity entity) { + return entity.getEntityId(); + } + + default boolean isGlowing(Entity entity) { + return entity.isGlowing(); + } + + default boolean isVisualFire(Entity entity) { + return entity.isVisualFire() || entity.getFireTicks() > 0; + } + + default int getFireTicks(Entity entity) { + return entity.getFireTicks(); + } + + default BoundingBox getBoundingBox(Entity entity) { + return entity.getBoundingBox(); + } + + default void getBoundingBox(Entity entity, BoundingBox dest) { + BoundingBox box = this.getBoundingBox(entity); + dest.resize(box.getMinX(), box.getMinY(), box.getMinZ(), box.getMaxX(), box.getMaxY(), box.getMaxZ()); + } + + default Set getCollidableExemptions(Entity entity) { + return entity instanceof LivingEntity living ? living.getCollidableExemptions() : null; + } + + default Component getCustomName(Entity entity) { + return entity.customName(); + } + + default void readEntityState(Entity entity, EntityState state) { + state.yRot = this.getYRot(entity); + state.yHeadRot = this.getYHeadRot(entity); + state.xHeadRot = this.getXHeadRot(entity); + state.yBodyRot = this.getYBodyRot(entity); + state.walking = this.isWalking(entity); + state.strafing = this.isStrafing(entity); + state.jumping = this.isJumping(entity); + state.flying = this.isFlying(entity); + state.health = this.getHealth(entity); + state.removed = this.isRemoved(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } + + default void getLocation(Entity entity, Location location) { + entity.getLocation(location); + } + + public static enum BoxRelToCam { + INSIDE, + POSITIVE, + NEGATIVE; + + public static EntityHandler.BoxRelToCam from(int min, int max, int pos) { + if (max > pos && min > pos) { + return POSITIVE; + } else { + return min < pos && max < pos ? NEGATIVE : INSIDE; + } + } + } + + @FunctionalInterface + public interface CullPointVisitor { + boolean visit(int var1, int var2, int var3); + } + + public static enum InteractionResult { + SUCCESS, + SUCCESS_NO_ITEM_USED, + CONSUME, + CONSUME_PARTIAL, + PASS, + FAIL; + } + + public static enum Point { + CORNER_A(0.0F, 0.0F, 0.0F), + CORNER_B(1.0F, 0.0F, 0.0F), + CORNER_C(0.0F, 1.0F, 0.0F), + CORNER_D(1.0F, 1.0F, 0.0F), + CORNER_E(0.0F, 0.0F, 1.0F), + CORNER_F(1.0F, 0.0F, 1.0F), + CORNER_G(0.0F, 1.0F, 1.0F), + CORNER_H(1.0F, 1.0F, 1.0F), + FACE_NX(0.0F, 0.5F, 0.5F), + FACE_PX(1.0F, 0.5F, 0.5F), + FACE_NY(0.5F, 0.0F, 0.5F), + FACE_PY(0.5F, 1.0F, 0.5F), + FACE_NZ(0.5F, 0.5F, 0.0F), + FACE_PZ(0.5F, 0.5F, 1.0F); + + public final float x; + public final float y; + public final float z; + + private Point(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/entity/EntityState.java b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/EntityState.java new file mode 100644 index 0000000..84814d2 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/EntityState.java @@ -0,0 +1,19 @@ +package com.ticxo.modelengine.api.nms.entity; + +import org.bukkit.util.BoundingBox; + +public final class EntityState { + public float yRot; + public float yHeadRot; + public float xHeadRot; + public float yBodyRot; + public float health; + public boolean walking; + public boolean strafing; + public boolean jumping; + public boolean flying; + public boolean removed; + public boolean glowing; + public boolean onFire; + public final BoundingBox boundingBox = new BoundingBox(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/entity/HitboxEntity.java b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/HitboxEntity.java new file mode 100644 index 0000000..1b3ea71 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/HitboxEntity.java @@ -0,0 +1,30 @@ +package com.ticxo.modelengine.api.nms.entity; + +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.UUID; +import org.bukkit.Location; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public interface HitboxEntity { + ModelBone getBone(); + + SubHitbox getSubHitbox(); + + int getEntityId(); + + UUID getUniqueId(); + + void queueLocation(Vector3f var1); + + Location getLocation(); + + @Nullable + OrientedBoundingBox getOrientedBoundingBox(); + + void markRemoved(); + + boolean isValid(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/BodyRotationController.java b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/BodyRotationController.java new file mode 100644 index 0000000..2e49045 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/BodyRotationController.java @@ -0,0 +1,89 @@ +package com.ticxo.modelengine.api.nms.entity.wrapper; + +import com.ticxo.modelengine.api.utils.data.io.DataIO; +import com.ticxo.modelengine.api.utils.data.io.SavedData; + +public interface BodyRotationController extends DataIO { + default void tick() { + } + + float getYHeadRot(); + + void setYHeadRot(float var1); + + float getXHeadRot(); + + void setXHeadRot(float var1); + + float getYBodyRot(); + + void setYBodyRot(float var1); + + boolean isHeadClampUneven(); + + void setHeadClampUneven(boolean var1); + + boolean isBodyClampUneven(); + + void setBodyClampUneven(boolean var1); + + float getMaxHeadAngle(); + + void setMaxHeadAngle(float var1); + + float getMaxBodyAngle(); + + void setMaxBodyAngle(float var1); + + float getMinHeadAngle(); + + void setMinHeadAngle(float var1); + + float getMinBodyAngle(); + + void setMinBodyAngle(float var1); + + float getStableAngle(); + + void setStableAngle(float var1); + + boolean isPlayerMode(); + + void setPlayerMode(boolean var1); + + int getRotationDelay(); + + void setRotationDelay(int var1); + + int getRotationDuration(); + + void setRotationDuration(int var1); + + @Override + default void save(SavedData data) { + data.putBoolean("head", this.isHeadClampUneven()); + data.putBoolean("body", this.isBodyClampUneven()); + data.putFloat("max_head", this.getMaxHeadAngle()); + data.putFloat("max_body", this.getMaxBodyAngle()); + data.putFloat("min_head", this.getMinHeadAngle()); + data.putFloat("min_body", this.getMinBodyAngle()); + data.putFloat("stable", this.getStableAngle()); + data.putBoolean("player", this.isPlayerMode()); + data.putInt("delay", this.getRotationDelay()); + data.putInt("duration", this.getRotationDuration()); + } + + @Override + default void load(SavedData data) { + this.setHeadClampUneven(data.getBoolean("head")); + this.setBodyClampUneven(data.getBoolean("body")); + this.setMaxHeadAngle(data.getFloat("max_head")); + this.setMaxBodyAngle(data.getFloat("max_body")); + this.setMinHeadAngle(data.getFloat("min_head")); + this.setMinBodyAngle(data.getFloat("min_body")); + this.setStableAngle(data.getFloat("stable")); + this.setPlayerMode(data.getBoolean("player")); + this.setRotationDelay(data.getInt("delay")); + this.setRotationDuration(data.getInt("duration")); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/LookController.java b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/LookController.java new file mode 100644 index 0000000..0d1ef54 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/LookController.java @@ -0,0 +1,16 @@ +package com.ticxo.modelengine.api.nms.entity.wrapper; + +public interface LookController { + void lookAt(double var1, double var3, double var5); + + void setPitch(float var1); + + void setHeadYaw(float var1); + + void setBodyYaw(float var1); + + default void setMovementOverride(MovementOverride override) { + } + + void defaultTick(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/MoveController.java b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/MoveController.java new file mode 100644 index 0000000..7833ed8 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/MoveController.java @@ -0,0 +1,42 @@ +package com.ticxo.modelengine.api.nms.entity.wrapper; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; + +public interface MoveController { + void move(float var1, float var2, float var3, float var4); + + void globalMove(float var1, float var2, float var3, float var4); + + void jump(); + + void setVelocity(double var1, double var3, double var5); + + void addVelocity(double var1, double var3, double var5); + + void nullifyFallDistance(); + + default void movePassenger(Entity entity, double x, double y, double z) { + ModelEngineAPI.getEntityHandler().movePassenger(entity, x, y, z); + } + + boolean isOnGround(); + + boolean isInWater(); + + float getSpeed(); + + Vector getVelocity(); + + void queuePostTick(Runnable var1); + + default void setMovementOverride(MovementOverride override) { + } + + default boolean ticksMountController() { + return true; + } + + void defaultTick(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/MovementOverride.java b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/MovementOverride.java new file mode 100644 index 0000000..2d07baf --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/MovementOverride.java @@ -0,0 +1,9 @@ +package com.ticxo.modelengine.api.nms.entity.wrapper; + +import com.ticxo.modelengine.api.model.ModeledEntity; + +public interface MovementOverride { + void updateMovement(MoveController var1, ModeledEntity var2); + + void updateDirection(LookController var1, ModeledEntity var2); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/TrackedEntity.java b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/TrackedEntity.java new file mode 100644 index 0000000..93fb872 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/entity/wrapper/TrackedEntity.java @@ -0,0 +1,62 @@ +package com.ticxo.modelengine.api.nms.entity.wrapper; + +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public interface TrackedEntity { + Predicate DEFAULT_PREDICATE = player -> true; + + Entity getEntity(); + + default int getInitialBaseRange() { + return 0; + } + + int getBaseRange(); + + void setBaseRange(int var1); + + int getEffectiveRange(); + + Set getTrackedPlayer(); + + Set getTrackedPlayer(Predicate var1); + + default Set getTrackedPlayer(Predicate predicate, Set dest) { + return this.getTrackedPlayer(predicate); + } + + default boolean isViewerSetUnchanged() { + return false; + } + + default void markViewersDirty() { + } + + void sendPairingData(Player var1); + + void broadcastSpawn(); + + void broadcastRemove(); + + void addForcedPairing(UUID var1); + + void removeForcedPairing(UUID var1); + + void clearForcedPairing(); + + void addForcedHidden(UUID var1); + + void removeForcedHidden(UUID var1); + + void clearForcedHidden(); + + void setPlayerPredicate(@NotNull Predicate var1); + + @NotNull + Predicate getPlayerPredicate(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/impl/DefaultBodyRotationController.java b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/DefaultBodyRotationController.java new file mode 100644 index 0000000..6032938 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/DefaultBodyRotationController.java @@ -0,0 +1,240 @@ +package com.ticxo.modelengine.api.nms.impl; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Mob; + +public class DefaultBodyRotationController implements BodyRotationController { + private final BaseEntity entity; + private float xHeadRot; + private float yHeadRot; + private float yBodyRot; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public DefaultBodyRotationController(BaseEntity entity) { + this.entity = entity; + this.syncFromBase(); + this.maxHeadAngle = 75.0F; + this.maxBodyAngle = 75.0F; + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void syncFromBase() { + this.xHeadRot = this.entity.getXHeadRot(); + this.yHeadRot = this.entity.getYHeadRot(); + this.yBodyRot = this.entity.getYBodyRot(); + } + + @Override + public void tick() { + this.xHeadRot = this.entity.getXHeadRot(); + this.yHeadRot = this.entity.getYHeadRot(); + if (this.entity.isWalking()) { + this.yBodyRot = this.entity.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + + private void rotateBodyIfNecessary() { + this.yBodyRot = TMath.rotateIfNecessary(this.yBodyRot, this.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle); + } + + private void rotateHeadIfNecessary() { + this.yHeadRot = TMath.rotateIfNecessary(this.yHeadRot, this.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.yBodyRot = TMath.rotateIfNecessary(this.yBodyRot, this.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + for (Entity entity : this.entity.getPassengers()) { + if (entity instanceof Mob) { + return false; + } + } + + return true; + } + + public BaseEntity getEntity() { + return this.entity; + } + + @Override + public float getXHeadRot() { + return this.xHeadRot; + } + + @Override + public float getYHeadRot() { + return this.yHeadRot; + } + + @Override + public float getYBodyRot() { + return this.yBodyRot; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setXHeadRot(float xHeadRot) { + this.xHeadRot = xHeadRot; + } + + @Override + public void setYHeadRot(float yHeadRot) { + this.yHeadRot = yHeadRot; + } + + @Override + public void setYBodyRot(float yBodyRot) { + this.yBodyRot = yBodyRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/impl/DummyTrackedEntity.java b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/DummyTrackedEntity.java new file mode 100644 index 0000000..481d560 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/DummyTrackedEntity.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.api.nms.impl; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +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.jetbrains.annotations.NotNull; + +public class DummyTrackedEntity implements TrackedEntity { + private final Set tracked = Sets.newConcurrentHashSet(); + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private int baseRange = 64; + private Predicate playerPredicate = DEFAULT_PREDICATE; + + public void detectPlayers(@NotNull Location location) { + World world = location.getWorld(); + if (world == null) { + throw new IllegalArgumentException("World of location cannot be null."); + } else { + int r2 = this.baseRange * this.baseRange; + this.tracked.clear(); + double lx = location.getX(); + double ly = location.getY(); + double lz = location.getZ(); + + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getWorld() == world) { + double dx = player.getX() - lx; + double dy = player.getY() - ly; + double dz = player.getZ() - lz; + if (dx * dx + dy * dy + dz * dz <= r2) { + this.tracked.add(player.getUniqueId()); + } + } + } + } + } + + @Override + public int getEffectiveRange() { + return this.baseRange; + } + + @Override + public Set getTrackedPlayer() { + HashSet set = new HashSet<>(this.forcedPairing); + + for (UUID player : this.tracked) { + Player p = Bukkit.getPlayer(player); + if (p != null && this.playerPredicate.test(p) && !this.forcedRemove.contains(player)) { + set.add(player); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + HashSet set = new HashSet<>(this.forcedPairing); + + for (UUID uuid : this.tracked) { + Player player = Bukkit.getPlayer(uuid); + if (predicate.test(player) && this.playerPredicate.test(player) && !this.forcedRemove.contains(uuid)) { + set.add(uuid); + } + } + + return set; + } + + @Override + public void addForcedPairing(UUID uuid) { + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @Override + public Entity getEntity() { + return null; + } + + @Override + public void sendPairingData(Player player) { + } + + @Override + public void broadcastSpawn() { + } + + @Override + public void broadcastRemove() { + } + + @Override + public int getBaseRange() { + return this.baseRange; + } + + @Override + public void setBaseRange(int baseRange) { + this.baseRange = baseRange; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyBodyRotationController.java b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyBodyRotationController.java new file mode 100644 index 0000000..bfe150a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyBodyRotationController.java @@ -0,0 +1,122 @@ +package com.ticxo.modelengine.api.nms.impl; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; + +public class EmptyBodyRotationController implements BodyRotationController { + @Override + public float getYHeadRot() { + return 0.0F; + } + + @Override + public void setYHeadRot(float rot) { + } + + @Override + public float getXHeadRot() { + return 0.0F; + } + + @Override + public void setXHeadRot(float rot) { + } + + @Override + public float getYBodyRot() { + return 0.0F; + } + + @Override + public void setYBodyRot(float rot) { + } + + @Override + public boolean isHeadClampUneven() { + return false; + } + + @Override + public void setHeadClampUneven(boolean flag) { + } + + @Override + public boolean isBodyClampUneven() { + return false; + } + + @Override + public void setBodyClampUneven(boolean flag) { + } + + @Override + public float getMaxHeadAngle() { + return 0.0F; + } + + @Override + public void setMaxHeadAngle(float angle) { + } + + @Override + public float getMaxBodyAngle() { + return 0.0F; + } + + @Override + public void setMaxBodyAngle(float angle) { + } + + @Override + public float getMinHeadAngle() { + return 0.0F; + } + + @Override + public void setMinHeadAngle(float angle) { + } + + @Override + public float getMinBodyAngle() { + return 0.0F; + } + + @Override + public void setMinBodyAngle(float angle) { + } + + @Override + public float getStableAngle() { + return 0.0F; + } + + @Override + public void setStableAngle(float angle) { + } + + @Override + public boolean isPlayerMode() { + return false; + } + + @Override + public void setPlayerMode(boolean flag) { + } + + @Override + public int getRotationDelay() { + return 0; + } + + @Override + public void setRotationDelay(int delay) { + } + + @Override + public int getRotationDuration() { + return 0; + } + + @Override + public void setRotationDuration(int duration) { + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyLookController.java b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyLookController.java new file mode 100644 index 0000000..69f4d65 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyLookController.java @@ -0,0 +1,25 @@ +package com.ticxo.modelengine.api.nms.impl; + +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; + +public class EmptyLookController implements LookController { + @Override + public void lookAt(double x, double y, double z) { + } + + @Override + public void setPitch(float pitch) { + } + + @Override + public void setHeadYaw(float yaw) { + } + + @Override + public void setBodyYaw(float yaw) { + } + + @Override + public void defaultTick() { + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyMoveController.java b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyMoveController.java new file mode 100644 index 0000000..1a0324a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/EmptyMoveController.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.api.nms.impl; + +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import org.bukkit.util.Vector; + +public class EmptyMoveController implements MoveController { + @Override + public void move(float side, float up, float front, float speedModifier) { + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + } + + @Override + public void jump() { + } + + @Override + public void setVelocity(double x, double y, double z) { + } + + @Override + public void addVelocity(double x, double y, double z) { + } + + @Override + public void nullifyFallDistance() { + } + + @Override + public boolean isOnGround() { + return false; + } + + @Override + public boolean isInWater() { + return false; + } + + @Override + public float getSpeed() { + return 0.0F; + } + + @Override + public Vector getVelocity() { + return new Vector(); + } + + @Override + public void queuePostTick(Runnable runnable) { + runnable.run(); + } + + @Override + public boolean ticksMountController() { + return false; + } + + @Override + public void defaultTick() { + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/impl/TempTrackedEntity.java b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/TempTrackedEntity.java new file mode 100644 index 0000000..0a5a447 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/impl/TempTrackedEntity.java @@ -0,0 +1,138 @@ +package com.ticxo.modelengine.api.nms.impl; + +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +public class TempTrackedEntity implements TrackedEntity { + private final Entity entity; + private final Set forcePaired = new HashSet<>(); + private final Set forceHidden = new HashSet<>(); + private int baseRange = -1; + private Predicate playerPredicate = DEFAULT_PREDICATE; + + @Override + public int getEffectiveRange() { + return this.baseRange; + } + + @Override + public Set getTrackedPlayer() { + if (ServerInfo.IS_PAPER) { + Set set = new HashSet<>(this.forcePaired); + + for (Player player : this.entity.getTrackedPlayers()) { + if (this.playerPredicate.test(player) && !this.forceHidden.contains(player.getUniqueId())) { + set.add(player.getUniqueId()); + } + } + + return set; + } else { + return new HashSet<>(); + } + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + if (ServerInfo.IS_PAPER) { + Set set = new HashSet<>(this.forcePaired); + + for (Player player : this.entity.getTrackedPlayers()) { + if (predicate.test(player) && this.playerPredicate.test(player) && !this.forceHidden.contains(player.getUniqueId())) { + set.add(player.getUniqueId()); + } + } + + return set; + } else { + return new HashSet<>(); + } + } + + @Override + public void sendPairingData(Player player) { + } + + @Override + public void broadcastSpawn() { + } + + @Override + public void broadcastRemove() { + } + + @Override + public void addForcedPairing(UUID uuid) { + this.forcePaired.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcePaired.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcePaired.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.forceHidden.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forceHidden.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forceHidden.clear(); + } + + public TempTrackedEntity(Entity entity) { + this.entity = entity; + } + + @Override + public Entity getEntity() { + return this.entity; + } + + public Set getForcePaired() { + return this.forcePaired; + } + + public Set getForceHidden() { + return this.forceHidden; + } + + @Override + public int getBaseRange() { + return this.baseRange; + } + + @Override + public void setBaseRange(int baseRange) { + this.baseRange = baseRange; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/network/CancelType.java b/api/src/main/java/com/ticxo/modelengine/api/nms/network/CancelType.java new file mode 100644 index 0000000..cab5fd5 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/network/CancelType.java @@ -0,0 +1,7 @@ +package com.ticxo.modelengine.api.nms.network; + +public enum CancelType { + SHOW, + HIDE, + INVIS; +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/network/ClientDesyncMonitor.java b/api/src/main/java/com/ticxo/modelengine/api/nms/network/ClientDesyncMonitor.java new file mode 100644 index 0000000..af95f62 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/network/ClientDesyncMonitor.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.api.nms.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.LinkedList; +import java.util.concurrent.atomic.AtomicInteger; + +public class ClientDesyncMonitor { + private static long CLIENT_SYNC_INTERVAL = 10000L; + private final PipelineWrapper pipeline; + private final LinkedList clientSyncTime = new LinkedList<>(); + private final AtomicInteger pingCounter = new AtomicInteger(); + private boolean testing; + private boolean hasPinged; + private volatile boolean pingSent; + private long lastTestTime; + private long clientSyncOrigin; + private long pongReceiveTime; + + public ClientDesyncMonitor(PipelineWrapper pipeline) { + this.pipeline = pipeline; + this.startTest(); + } + + public void startTest() { + this.testing = true; + this.hasPinged = false; + this.pingSent = false; + ModelEngineAPI.getAPI().getModelUpdaters().startDesyncMonitor(this.pipeline.getPlayer().getUniqueId()); + } + + public boolean shouldPing() { + return this.testing && !this.pingSent; + } + + public void markPingSent() { + this.pingSent = true; + } + + public void stopTest() { + this.testing = false; + this.lastTestTime = System.currentTimeMillis(); + ModelEngineAPI.getAPI().getModelUpdaters().stopDesyncMonitor(this.pipeline.getPlayer().getUniqueId()); + if (!this.clientSyncTime.isEmpty()) { + this.clientSyncOrigin = this.clientSyncTime.getLast(); + long delta = (this.clientSyncOrigin - this.pongReceiveTime) % 50L; + long deviation = Math.abs(delta - 25L); + if (deviation <= 15L) { + this.pipeline.setDelay(0L); + } else { + if (delta > 25L) { + this.pipeline.setDelay(delta - 25L); + } else { + this.pipeline.setDelay(delta + 25L); + } + } + } + } + + public void recordClientSyncTime(long time) { + this.clientSyncTime.add(time); + if (this.clientSyncTime.size() > 10) { + this.clientSyncTime.poll(); + } + + if (time > this.pongReceiveTime && this.testing && this.hasPinged) { + this.stopTest(); + } + } + + public void recordPongTime(long time) { + if (this.testing) { + this.pongReceiveTime = time; + if (!this.clientSyncTime.isEmpty()) { + if (time > this.clientSyncTime.getLast()) { + this.hasPinged = true; + } + } + } + } + + public boolean clientTickShifted() { + if (this.clientSyncTime.isEmpty()) { + return true; + } else { + long last = this.clientSyncTime.getLast(); + return (last - this.clientSyncOrigin) % 50L < 40L; + } + } + + public boolean shouldRetest() { + return System.currentTimeMillis() - this.lastTestTime > CLIENT_SYNC_INTERVAL; + } + + public PipelineWrapper getPipeline() { + return this.pipeline; + } + + public LinkedList getClientSyncTime() { + return this.clientSyncTime; + } + + public AtomicInteger getPingCounter() { + return this.pingCounter; + } + + public boolean isTesting() { + return this.testing; + } + + public boolean isHasPinged() { + return this.hasPinged; + } + + public boolean isPingSent() { + return this.pingSent; + } + + public long getLastTestTime() { + return this.lastTestTime; + } + + public long getClientSyncOrigin() { + return this.clientSyncOrigin; + } + + public long getPongReceiveTime() { + return this.pongReceiveTime; + } + + public void setTesting(boolean testing) { + this.testing = testing; + } + + public void setHasPinged(boolean hasPinged) { + this.hasPinged = hasPinged; + } + + public void setPingSent(boolean pingSent) { + this.pingSent = pingSent; + } + + public void setLastTestTime(long lastTestTime) { + this.lastTestTime = lastTestTime; + } + + public void setClientSyncOrigin(long clientSyncOrigin) { + this.clientSyncOrigin = clientSyncOrigin; + } + + public void setPongReceiveTime(long pongReceiveTime) { + this.pongReceiveTime = pongReceiveTime; + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> CLIENT_SYNC_INTERVAL = ConfigProperty.CLIENT_SYNC_INTERVAL.getInt()); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/network/ModPlayerTracker.java b/api/src/main/java/com/ticxo/modelengine/api/nms/network/ModPlayerTracker.java new file mode 100644 index 0000000..f8c3df9 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/network/ModPlayerTracker.java @@ -0,0 +1,26 @@ +package com.ticxo.modelengine.api.nms.network; + +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +public class ModPlayerTracker { + public static final String CHANNEL = "modelengine:bulk_data"; + private static final Set MOD_PLAYERS = ConcurrentHashMap.newKeySet(); + + public static void addPlayer(UUID uuid) { + MOD_PLAYERS.add(uuid); + } + + public static void removePlayer(UUID uuid) { + MOD_PLAYERS.remove(uuid); + } + + public static boolean hasClientMod(UUID uuid) { + return MOD_PLAYERS.contains(uuid); + } + + public static Set getModPlayers() { + return MOD_PLAYERS; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/network/NetworkHandler.java b/api/src/main/java/com/ticxo/modelengine/api/nms/network/NetworkHandler.java new file mode 100644 index 0000000..ffea21e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/network/NetworkHandler.java @@ -0,0 +1,25 @@ +package com.ticxo.modelengine.api.nms.network; + +import java.util.Optional; +import java.util.UUID; +import org.bukkit.entity.Player; + +public interface NetworkHandler { + int getProtocolVersion(); + + Optional getPipeline(UUID var1); + + void removePipeline(UUID var1); + + void injectChannel(Player var1); + + void ejectChannel(Player var1); + + void ping(UUID var1); + + void startBatch(); + + boolean isBatching(); + + void endBatch(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/network/PipelineWrapper.java b/api/src/main/java/com/ticxo/modelengine/api/nms/network/PipelineWrapper.java new file mode 100644 index 0000000..de2fda4 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/network/PipelineWrapper.java @@ -0,0 +1,120 @@ +package com.ticxo.modelengine.api.nms.network; + +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import io.netty.channel.Channel; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; + +public class PipelineWrapper { + private final Player player; + private final Channel channel; + private final boolean fakeChannel; + private final Consumer flushAndWrite; + private final ClientDesyncMonitor desyncMonitor; + private final Queue delayedPackets = new ConcurrentLinkedQueue<>(); + private final AtomicBoolean drainScheduled = new AtomicBoolean(); + private long delay; + + public PipelineWrapper(Player player, Channel channel) { + this.player = player; + this.channel = channel; + this.fakeChannel = isFakeChannel(channel); + if (this.fakeChannel) { + TLogger.warn("Model packets will not be sent to " + player.getName() + ": " + channel.getClass().getName() + " is not a standard player connection."); + this.flushAndWrite = msg -> {}; + } else { + this.flushAndWrite = msg -> { + if (channel.isActive()) { + channel.writeAndFlush(msg); + } + }; + } + + this.desyncMonitor = new ClientDesyncMonitor(this); + } + + private static boolean isFakeChannel(Channel channel) { + try { + return channel.eventLoop().inEventLoop(); + } catch (Throwable var2) { + return true; + } + } + + public void setDelay(long delay) { + this.delay = delay; + if (DebugToggle.isDebugging(DebugToggle.NOTIFY_DESYNC)) { + this.player.sendMessage(Component.text("Client delay: " + delay)); + } + } + + public void writeAndFlush(Object object) { + long delay = this.delay; + if (delay > 0L && !this.fakeChannel) { + this.delayedPackets.add(new PipelineWrapper.DelayedPacket(System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(delay), object)); + if (this.drainScheduled.compareAndSet(false, true)) { + this.channel.eventLoop().schedule(this::drainDelayed, delay, TimeUnit.MILLISECONDS); + } + } else { + this.flushAndWrite.accept(object); + } + } + + public void writeAndFlushNow(Object object) { + this.flushAndWrite.accept(object); + } + + private void drainDelayed() { + while (true) { + PipelineWrapper.DelayedPacket packet; + if ((packet = this.delayedPackets.peek()) != null) { + long wait = packet.sendTime() - System.nanoTime(); + if (wait > 0L) { + this.channel.eventLoop().schedule(this::drainDelayed, wait, TimeUnit.NANOSECONDS); + return; + } + + this.delayedPackets.poll(); + this.flushAndWrite.accept(packet.object()); + } else { + this.drainScheduled.set(false); + if (this.delayedPackets.isEmpty() || !this.drainScheduled.compareAndSet(false, true)) { + return; + } + } + } + } + + public Player getPlayer() { + return this.player; + } + + public Channel getChannel() { + return this.channel; + } + + public boolean isFakeChannel() { + return this.fakeChannel; + } + + public Consumer getFlushAndWrite() { + return this.flushAndWrite; + } + + public ClientDesyncMonitor getDesyncMonitor() { + return this.desyncMonitor; + } + + public long getDelay() { + return this.delay; + } + + private record DelayedPacket(long sendTime, Object object) { + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/network/ProtectedPacket.java b/api/src/main/java/com/ticxo/modelengine/api/nms/network/ProtectedPacket.java new file mode 100644 index 0000000..acd0878 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/network/ProtectedPacket.java @@ -0,0 +1,4 @@ +package com.ticxo.modelengine.api.nms.network; + +public record ProtectedPacket(Object packet) { +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/network/ProtectedPacketUnpacker.java b/api/src/main/java/com/ticxo/modelengine/api/nms/network/ProtectedPacketUnpacker.java new file mode 100644 index 0000000..4f15b5f --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/network/ProtectedPacketUnpacker.java @@ -0,0 +1,15 @@ +package com.ticxo.modelengine.api.nms.network; + +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; + +public class ProtectedPacketUnpacker extends ChannelDuplexHandler { + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (msg instanceof ProtectedPacket protectedPacket) { + msg = protectedPacket.packet(); + } + + super.write(ctx, msg, promise); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/nms/ui/AnvilHandler.java b/api/src/main/java/com/ticxo/modelengine/api/nms/ui/AnvilHandler.java new file mode 100644 index 0000000..519e4ed --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/nms/ui/AnvilHandler.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.api.nms.ui; + +import java.util.function.Function; +import java.util.function.Supplier; +import org.bukkit.entity.Player; + +public interface AnvilHandler { + void openAnvil(Player var1, Function var2, Supplier var3); + + void reopenAnvil(Player var1); + + void consumeConfirm(Player var1); + + void consumeClose(Player var1); + + void removeAnvil(Player var1); + + void closeAnvil(Player var1); + + boolean isListening(Player var1); + + AnvilHandler.Menu getAnvilMenu(Player var1); + + public static class Menu { + private final int id; + private final Function onInput; + private final Supplier onClose; + private String value; + + public boolean confirm() { + return this.onInput.apply(this.value); + } + + public boolean close() { + return this.onClose.get(); + } + + public Menu(int id, Function onInput, Supplier onClose) { + this.id = id; + this.onInput = onInput; + this.onClose = onClose; + } + + public int getId() { + return this.id; + } + + public Function getOnInput() { + return this.onInput; + } + + public Supplier getOnClose() { + return this.onClose; + } + + public String getValue() { + return this.value; + } + + public void setValue(String value) { + this.value = value; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/CompatibilityManager.java b/api/src/main/java/com/ticxo/modelengine/api/utils/CompatibilityManager.java new file mode 100644 index 0000000..6da6f80 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/CompatibilityManager.java @@ -0,0 +1,66 @@ +package com.ticxo.modelengine.api.utils; + +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class CompatibilityManager implements Listener { + private final PluginManager pluginManager; + private final Set allPlugins = Sets.newConcurrentHashSet(); + private final Map> compatibilities = Maps.newConcurrentMap(); + + public CompatibilityManager(JavaPlugin plugin) { + this.pluginManager = Bukkit.getPluginManager(); + + for (Plugin pluginManagerPlugin : this.pluginManager.getPlugins()) { + this.allPlugins.add(pluginManagerPlugin.getName()); + } + + this.pluginManager.registerEvents(this, plugin); + } + + public void registerSupport(String pluginName, Supplier configuration) { + if (this.allPlugins.contains(pluginName)) { + Plugin plugin = this.pluginManager.getPlugin(pluginName); + MemoizeSupplier memoize = MemoizeSupplier.of(configuration); + if (plugin != null && plugin.isEnabled() && memoize.get().tryApply(plugin)) { + TLogger.log("Compatibility applied: " + plugin.getName()); + } else { + this.compatibilities.put(pluginName, memoize); + } + } + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + public void onPluginLoad(PluginEnableEvent event) { + Plugin plugin = event.getPlugin(); + if (plugin.isEnabled()) { + MemoizeSupplier config = this.compatibilities.get(plugin.getName()); + if (config != null) { + if (!config.get().tryApply(plugin)) { + TLogger.error("Failed to apply compatibility support for " + plugin.getName() + "."); + } else { + TLogger.log("Compatibility applied: " + plugin.getName()); + } + } + } + } + + @FunctionalInterface + public interface CompatibilityConfiguration { + boolean tryApply(Plugin var1); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/MemoizeSupplier.java b/api/src/main/java/com/ticxo/modelengine/api/utils/MemoizeSupplier.java new file mode 100644 index 0000000..6689d6d --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/MemoizeSupplier.java @@ -0,0 +1,26 @@ +package com.ticxo.modelengine.api.utils; + +import java.util.function.Supplier; + +public class MemoizeSupplier { + private final Supplier supplier; + private boolean initialized; + private T value; + + public T get() { + if (!this.initialized) { + this.value = this.supplier.get(); + this.initialized = true; + } + + return this.value; + } + + public static MemoizeSupplier of(Supplier supplier) { + return new MemoizeSupplier<>(supplier); + } + + public MemoizeSupplier(Supplier supplier) { + this.supplier = supplier; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/MiscUtils.java b/api/src/main/java/com/ticxo/modelengine/api/utils/MiscUtils.java new file mode 100644 index 0000000..a964926 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/MiscUtils.java @@ -0,0 +1,95 @@ +package com.ticxo.modelengine.api.utils; + +import it.unimi.dsi.fastutil.Pair; +import java.nio.charset.StandardCharsets; +import java.text.DecimalFormat; +import java.util.UUID; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class MiscUtils { + public static final DecimalFormat FORMATTER = new DecimalFormat() { + { + this.setMaximumFractionDigits(1); + this.setMinimumFractionDigits(1); + } + }; + + @SafeVarargs + @NotNull + public static T or(T... values) { + for (T v : values) { + if (v != null) { + return v; + } + } + + throw new RuntimeException("All values are null"); + } + + @SafeVarargs + @NotNull + public static T orDef(@NotNull T def, T... values) { + for (T v : values) { + if (v != null) { + return v; + } + } + + return def; + } + + public static boolean isJava21OrHigher() { + return isJavaVersionOrHigher(21); + } + + public static boolean isJava25OrHigher() { + return isJavaVersionOrHigher(25); + } + + public static boolean isJavaVersionOrHigher(int v) { + try { + int version = Runtime.version().feature(); + return version >= v; + } catch (Exception var3) { + int versionx = Integer.parseInt(System.getProperty("java.version")); + return versionx >= v; + } + } + + public static UUID generateUUIDFromString(String input) { + return UUID.nameUUIDFromBytes(input.getBytes(StandardCharsets.UTF_8)); + } + + public static Pair getAnimationRef(String animation) { + if (animation.startsWith("ref[") && animation.endsWith("]")) { + animation = animation.substring(4, animation.length() - 1); + String[] split = animation.split("\\.", 2); + if (split.length >= 2) { + return Pair.of(split[0], split[1]); + } + } + + return Pair.of(null, animation); + } + + public static String createAnimationRef(String model, String animation) { + return model == null ? animation : "ref[" + model + "." + animation + "]"; + } + + public static T handle(T val, @Nullable Throwable throwable) { + if (throwable != null) { + throwable.printStackTrace(); + } + + return null; + } + + public static void pfx(Location location, Color color, float size) { + location.getWorld().spawnParticle(Particle.REDSTONE, location, 1, new DustOptions(color, size)); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/MojangAPI.java b/api/src/main/java/com/ticxo/modelengine/api/utils/MojangAPI.java new file mode 100644 index 0000000..0a06549 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/MojangAPI.java @@ -0,0 +1,202 @@ +package com.ticxo.modelengine.api.utils; + +import com.destroystokyo.paper.profile.PlayerProfile; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.utils.data.GSONUtils; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpResponse.BodyHandlers; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import org.bukkit.Bukkit; +import org.bukkit.profile.PlayerTextures; +import org.bukkit.profile.PlayerTextures.SkinModel; +import org.jetbrains.annotations.NotNull; + +public class MojangAPI { + private static final HttpClient CLIENT = HttpClient.newHttpClient(); + private static final Map UUID_CACHE = new ConcurrentHashMap<>(); + private static final Map DATA_CACHE = new ConcurrentHashMap<>(); + private static final Map SKIN_CACHE = new ConcurrentHashMap<>(); + + private MojangAPI() { + throw new IllegalStateException(); + } + + public static CompletableFuture getRawSkinData(PlayerProfile profile) { + try { + URL skin = profile.getTextures().getSkin(); + if (skin == null) { + return CompletableFuture.failedFuture(new RuntimeException("Skin URL is null")); + } else { + URI uri = skin.toURI(); + String key = uri.toString(); + String data = SKIN_CACHE.get(key); + if (data != null) { + return CompletableFuture.completedFuture(data); + } else { + HttpRequest request = HttpRequest.newBuilder().uri(uri).timeout(Duration.of(30L, ChronoUnit.SECONDS)).GET().build(); + return CompletableFuture.supplyAsync(() -> readPersistedSkin(key)).thenCompose(persisted -> { + if (persisted != null) { + SKIN_CACHE.put(key, persisted); + return CompletableFuture.completedFuture(persisted); + } else { + return CLIENT.sendAsync(request, BodyHandlers.ofByteArray()).thenApply(response -> { + if (response.statusCode() != 200) { + throw new RuntimeException("Skin download failed with HTTP " + response.statusCode() + ": " + key); + } else { + String base64 = Base64.getEncoder().encodeToString(response.body()); + SKIN_CACHE.put(key, base64); + writePersistedSkin(key, base64); + return base64; + } + }); + } + }); + } + } + } catch (URISyntaxException var6) { + throw new RuntimeException(var6); + } + } + + private static File persistedSkinFile(String url) { + String id = UUID.nameUUIDFromBytes(url.getBytes(StandardCharsets.UTF_8)).toString(); + return new File(ModelEngineAPI.getAPI().getDataFolder(), ".data/skincache/" + id + ".b64"); + } + + private static String readPersistedSkin(String url) { + File file = persistedSkinFile(url); + if (!file.isFile()) { + return null; + } else { + try { + String base64 = Files.readString(file.toPath(), StandardCharsets.US_ASCII).strip(); + return base64.isEmpty() ? null : base64; + } catch (IOException var3) { + TLogger.warn("Failed to read cached skin " + file + ": " + var3); + return null; + } + } + } + + private static void writePersistedSkin(String url, String base64) { + Path target = persistedSkinFile(url).toPath(); + + try { + Files.createDirectories(target.getParent()); + Path temp = Files.createTempFile(target.getParent(), "skin", ".tmp"); + + try { + Files.writeString(temp, base64, StandardCharsets.US_ASCII); + Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE); + } finally { + Files.deleteIfExists(temp); + } + } catch (IOException var8) { + if (!Files.isRegularFile(target)) { + TLogger.warn("Failed to cache skin " + target + ": " + var8); + } + } + } + + public static PlayerProfile fromBase64(@NotNull String data) { + PlayerProfile profile = Bukkit.createProfile(UUID.randomUUID()); + String decoded = new String(Base64.getDecoder().decode(data)); + JsonObject root = (JsonObject)ModelEngineAPI.getAPI().getGson().fromJson(decoded, JsonObject.class); + GSONUtils.ifPresent(root, "textures", element -> GSONUtils.ifPresent(element, "SKIN", element1 -> { + String url = GSONUtils.get(element1, "url", JsonElement::getAsString); + if (url == null) { + throw new NullPointerException("Skin URL cannot be null."); + } else { + JsonObject metadata = GSONUtils.get(element1, "metadata", JsonElement::getAsJsonObject); + boolean slim = GSONUtils.get(metadata, "model", element2 -> element2.getAsString().equals("slim"), false); + + try { + PlayerTextures texture = profile.getTextures(); + texture.setSkin(new URL(url), slim ? SkinModel.SLIM : SkinModel.CLASSIC); + profile.setTextures(texture); + } catch (MalformedURLException var6) { + throw new RuntimeException(var6); + } + } + })); + return profile; + } + + public static PlayerProfile fromUUID(UUID uuid) { + String data = DATA_CACHE.computeIfAbsent( + uuid, + uuid1 -> { + try { + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid)) + .timeout(Duration.of(30L, ChronoUnit.SECONDS)) + .GET() + .build(); + String result = CLIENT.sendAsync(request, BodyHandlers.ofString()).thenApply(HttpResponse::body).get(30L, TimeUnit.SECONDS); + JsonObject root = (JsonObject)ModelEngineAPI.getAPI().getGson().fromJson(result, JsonObject.class); + return GSONUtils.get(root, "properties", element -> { + JsonArray array = element.getAsJsonArray(); + return array.isEmpty() ? null : GSONUtils.get(array.get(0), "value", JsonElement::getAsString); + }); + } catch (Throwable var5) { + throw new RuntimeException(var5); + } + } + ); + return data == null ? null : fromBase64(data); + } + + public static UUID getUUIDFromUsername(String username) { + return UUID_CACHE.computeIfAbsent( + username, + s -> { + try { + long time = System.currentTimeMillis() / 1000L; + HttpRequest request = HttpRequest.newBuilder() + .uri(new URI("https://api.mojang.com/users/profiles/minecraft/" + username + "?at=" + time)) + .timeout(Duration.of(30L, ChronoUnit.SECONDS)) + .GET() + .build(); + String result = CLIENT.sendAsync(request, BodyHandlers.ofString()).thenApply(HttpResponse::body).get(30L, TimeUnit.SECONDS); + JsonObject root = (JsonObject)ModelEngineAPI.getAPI().getGson().fromJson(result, JsonObject.class); + return GSONUtils.get(root, "id", element -> TMath.parseUUID(element.getAsString())); + } catch (Throwable var7) { + throw new RuntimeException(var7); + } + } + ); + } + + public static Promise fromUUIDPromise(UUID uuid) { + return Promise.supplyingAsync(() -> fromUUID(uuid)); + } + + public static Promise getUUIDFromUsernamePromise(String name) { + return Promise.supplyingAsync(() -> getUUIDFromUsername(name)); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/OffsetMode.java b/api/src/main/java/com/ticxo/modelengine/api/utils/OffsetMode.java new file mode 100644 index 0000000..53ba0c1 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/OffsetMode.java @@ -0,0 +1,15 @@ +package com.ticxo.modelengine.api.utils; + +public enum OffsetMode { + LOCAL, + MODEL, + GLOBAL; + + public static OffsetMode get(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException var2) { + return LOCAL; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/Profiler.java b/api/src/main/java/com/ticxo/modelengine/api/utils/Profiler.java new file mode 100644 index 0000000..5980bd7 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/Profiler.java @@ -0,0 +1,54 @@ +package com.ticxo.modelengine.api.utils; + +import java.util.LinkedList; +import java.util.Queue; + +public class Profiler { + private final Queue times; + private final int maxSize; + private long startTime; + + public Profiler(int maxSize) { + this.maxSize = maxSize; + this.times = new LinkedList<>(); + } + + public void startProfiling() { + this.startTime = System.nanoTime(); + } + + public void stopProfiling() { + if (this.startTime == 0L) { + throw new IllegalStateException("Profiling has not been started."); + } else { + long endTime = System.nanoTime(); + long duration = endTime - this.startTime; + this.addTime(duration); + this.startTime = 0L; + } + } + + private void addTime(long duration) { + if (this.times.size() >= this.maxSize) { + this.times.poll(); + } + + this.times.offer(duration); + } + + public long getMinTime() { + return this.times.stream().min(Long::compare).orElse(0L); + } + + public long getMaxTime() { + return this.times.stream().max(Long::compare).orElse(0L); + } + + public double getAverageTime() { + return this.times.stream().mapToLong(Long::longValue).average().orElse(0.0); + } + + public int getSampleSize() { + return this.times.size(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/RaceConditionUtil.java b/api/src/main/java/com/ticxo/modelengine/api/utils/RaceConditionUtil.java new file mode 100644 index 0000000..0185709 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/RaceConditionUtil.java @@ -0,0 +1,46 @@ +package com.ticxo.modelengine.api.utils; + +import com.ticxo.modelengine.api.utils.ticker.DualTicker; +import java.util.ConcurrentModificationException; + +public class RaceConditionUtil { + public static void wrapConmod(Runnable runnable) { + wrapConmod(runnable, 1); + } + + public static void wrapConmod(Runnable runnable, int delay) { + wrapConmod(runnable, delay, 1); + } + + public static void wrapConmod(Runnable runnable, int delay, int attempts) { + try { + runnable.run(); + } catch (ConcurrentModificationException var4) { + if (attempts > 0) { + DualTicker.queueDelayedSyncTask(() -> wrapConmod(runnable, delay, attempts - 1), delay); + } + } catch (Throwable var5) { + var5.printStackTrace(); + } + } + + public static void wrapAll(Runnable runnable) { + wrapAll(runnable, 1); + } + + public static void wrapAll(Runnable runnable, int delay) { + wrapAll(runnable, delay, 1); + } + + public static void wrapAll(Runnable runnable, int delay, int attempts) { + try { + runnable.run(); + } catch (Throwable var4) { + if (attempts > 0) { + DualTicker.queueDelayedSyncTask(() -> wrapConmod(runnable, delay, attempts - 1), delay); + } else { + var4.printStackTrace(); + } + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/ReflectionUtils.java b/api/src/main/java/com/ticxo/modelengine/api/utils/ReflectionUtils.java new file mode 100644 index 0000000..774546b --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/ReflectionUtils.java @@ -0,0 +1,203 @@ +package com.ticxo.modelengine.api.utils; + +import com.google.common.collect.Maps; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.jetbrains.annotations.Nullable; + +public class ReflectionUtils { + private static final Map, Class> PRIMITIVE_EQUIV = new HashMap, Class>() { + { + this.put(byte.class, Byte.class); + this.put(short.class, Short.class); + this.put(int.class, Integer.class); + this.put(long.class, Long.class); + this.put(float.class, Float.class); + this.put(double.class, Double.class); + this.put(boolean.class, Boolean.class); + this.put(char.class, Character.class); + } + }; + private static final Map, ConcurrentHashMap> DYNAMIC_FIELDS = Maps.newConcurrentMap(); + private static final Map, ConcurrentHashMap> FIELD_MAP = Maps.newConcurrentMap(); + private static final Map, ConcurrentHashMap> METHOD_MAP = Maps.newConcurrentMap(); + private static final boolean IS_MAPPED = Boolean.getBoolean("modelengine.mapped"); + + public static Field unlockField(ReflectionUtils.ReflectionEnum field) { + try { + Field f = field.getTarget().getDeclaredField(field.get(IS_MAPPED)); + f.setAccessible(true); + return f; + } catch (SecurityException | IllegalArgumentException | NoSuchFieldException var4) { + try { + Field fx = field.getTarget().getDeclaredField(field.get(!IS_MAPPED)); + fx.setAccessible(true); + return fx; + } catch (SecurityException | IllegalArgumentException | NoSuchFieldException var3) { + throw new RuntimeException("An error occurred while unlocking field: " + field.getMapped(), var4); + } + } + } + + public static Method unlockMethod(ReflectionUtils.MethodEnum method) { + try { + Method m = method.getTarget().getDeclaredMethod(method.get(IS_MAPPED), method.getParameterClasses()); + m.setAccessible(true); + return m; + } catch (SecurityException | IllegalArgumentException | NoSuchMethodException var4) { + try { + Method mx = method.getTarget().getDeclaredMethod(method.get(!IS_MAPPED), method.getParameterClasses()); + mx.setAccessible(true); + return mx; + } catch (SecurityException | IllegalArgumentException | NoSuchMethodException var3) { + throw new RuntimeException("An error occurred while unlocking method: " + method.getMapped(), var4); + } + } + } + + public static Field getField(Class clazz, String field) { + return getField( + DYNAMIC_FIELDS.computeIfAbsent(clazz, aClass -> new ConcurrentHashMap<>()) + .computeIfAbsent(field, s -> new ReflectionUtils.RuntimeReflection(clazz, field)) + ); + } + + public static Field getField(ReflectionUtils.ReflectionEnum field) { + return FIELD_MAP.computeIfAbsent(field.getTarget(), aClass -> new ConcurrentHashMap<>()).computeIfAbsent(field, ReflectionUtils::unlockField); + } + + public static Method getMethod(ReflectionUtils.MethodEnum method) { + return METHOD_MAP.computeIfAbsent(method.getTarget(), aClass -> new ConcurrentHashMap<>()).computeIfAbsent(method, ReflectionUtils::unlockMethod); + } + + @Nullable + public static T get(Object object, ReflectionUtils.ReflectionEnum field) { + try { + return (T)getField(field).get(object); + } catch (IllegalAccessException var3) { + var3.printStackTrace(); + return null; + } + } + + @Nullable + public static T get(Object object, ReflectionUtils.ReflectionEnum field, T def) { + try { + return (T)getField(field).get(object); + } catch (IllegalAccessException var4) { + var4.printStackTrace(); + return def; + } + } + + @Nullable + public static T get(ReflectionUtils.ReflectionEnum field) { + return get(null, field); + } + + public static boolean set(Object object, ReflectionUtils.ReflectionEnum field, Object val) { + try { + getField(field).set(object, val); + return true; + } catch (IllegalAccessException var4) { + var4.printStackTrace(); + return false; + } + } + + public static boolean set(ReflectionUtils.ReflectionEnum field, Object val) { + return set(null, field, val); + } + + public static T call(Object object, ReflectionUtils.MethodEnum method, Object... parameters) { + try { + Class[] paramClasses = method.getParameterClasses(); + if (paramClasses.length > parameters.length) { + throw new RuntimeException(String.format("Invalid method call: Missing parameters. Expected %s, got %s.", paramClasses.length, parameters.length)); + } else { + for (int i = 0; i < paramClasses.length; i++) { + Class givenClass = parameters[i].getClass(); + Class expectClass = paramClasses[i]; + if (!expectClass.isAssignableFrom(givenClass) && isDifferentPrimitive(givenClass, expectClass)) { + throw new RuntimeException( + String.format( + "Invalid method call: Invalid parameter at position %s. Expected %s, got %s.", + i, + expectClass.getSimpleName(), + givenClass.getSimpleName() + ) + ); + } + } + + Method m = getMethod(method); + return (T)m.invoke(object, parameters); + } + } catch (InvocationTargetException | IllegalAccessException var7) { + var7.printStackTrace(); + return null; + } + } + + public static T call(ReflectionUtils.MethodEnum method, Object... parameters) { + return call(null, method, parameters); + } + + private static boolean isDifferentPrimitive(Class givenClass, Class expectClass) { + if (!expectClass.isPrimitive()) { + return true; + } else { + Class boxed = PRIMITIVE_EQUIV.get(expectClass); + return !boxed.isAssignableFrom(givenClass); + } + } + + public interface MethodEnum extends ReflectionUtils.ReflectionEnum { + Class[] getParameterClasses(); + } + + public interface ReflectionEnum { + Class getTarget(); + + String getObfuscated(); + + String getMapped(); + + default String get(boolean mapped) { + return mapped ? this.getMapped() : this.getObfuscated(); + } + } + + static class RuntimeReflection implements ReflectionUtils.ReflectionEnum { + private final Class target; + private final String field; + + @Override + public String getObfuscated() { + return this.field; + } + + @Override + public String getMapped() { + return this.field; + } + + public RuntimeReflection(Class target, String field) { + this.target = target; + this.field = field; + } + + @Override + public Class getTarget() { + return this.target; + } + + public String getField() { + return this.field; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/RunnableGroup.java b/api/src/main/java/com/ticxo/modelengine/api/utils/RunnableGroup.java new file mode 100644 index 0000000..66e44f8 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/RunnableGroup.java @@ -0,0 +1,16 @@ +package com.ticxo.modelengine.api.utils; + +import java.util.ArrayList; +import java.util.List; + +public class RunnableGroup { + private final List runnables = new ArrayList<>(); + + public void add(Runnable runnable) { + this.runnables.add(runnable); + } + + public void execute() { + this.runnables.forEach(Runnable::run); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/StepFlag.java b/api/src/main/java/com/ticxo/modelengine/api/utils/StepFlag.java new file mode 100644 index 0000000..094b0e6 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/StepFlag.java @@ -0,0 +1,17 @@ +package com.ticxo.modelengine.api.utils; + +import com.ticxo.modelengine.api.utils.math.TMath; + +public enum StepFlag { + POSITION, + ROTATION, + SCALE; + + public byte setStep(byte data, boolean flag) { + return TMath.setBit(data, this.ordinal(), flag); + } + + public boolean isStepping(byte data) { + return TMath.getBit(data, this.ordinal()); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/TFile.java b/api/src/main/java/com/ticxo/modelengine/api/utils/TFile.java new file mode 100644 index 0000000..c9f0373 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/TFile.java @@ -0,0 +1,238 @@ +package com.ticxo.modelengine.api.utils; + +import com.google.common.io.ByteStreams; +import com.ticxo.modelengine.api.utils.data.ResourceLocation; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.awt.image.BufferedImage; +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.Base64; +import java.util.Map; +import java.util.Map.Entry; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; +import javax.imageio.ImageIO; +import org.bukkit.plugin.java.JavaPlugin; + +public class TFile { + public static final String SEP = System.getProperty("file.separator"); + + public static File copyResource(JavaPlugin plugin, File file, String path) { + if (!file.exists()) { + try { + OutputStream writer = new FileOutputStream(file); + InputStream reader = plugin.getResource(path); + if (reader != null) { + ByteStreams.copy(reader, writer); + } + + writer.close(); + } catch (IOException var5) { + var5.printStackTrace(); + } + } + + return file; + } + + public static File copyResource(JavaPlugin plugin, File origin, String resourceOrigin, String path) { + return copyResource(plugin, createFile(origin, path), resourceOrigin + "/" + path); + } + + public static File copyResource(JavaPlugin plugin, File origin, String resourceOrigin, String srcPath, String destPath) { + return copyResource(plugin, createFile(origin, destPath), resourceOrigin + "/" + srcPath); + } + + public static File copyResourceTemplated( + JavaPlugin plugin, File origin, String resourceOrigin, String srcPath, String destPath, Map replacements + ) { + File file = createFile(origin, destPath); + if (file.exists()) { + return file; + } else { + try { + File var14; + try (InputStream reader = plugin.getResource(resourceOrigin + "/" + srcPath)) { + if (reader != null) { + String content = new String(reader.readAllBytes(), StandardCharsets.UTF_8); + + for (Entry entry : replacements.entrySet()) { + content = content.replace(entry.getKey(), entry.getValue()); + } + + Files.writeString(file.toPath(), content, StandardCharsets.UTF_8); + return file; + } + + var14 = file; + } + + return var14; + } catch (IOException var13) { + var13.printStackTrace(); + return file; + } + } + } + + public static String createPath(String... path) { + if (path.length == 0) { + return ""; + } else { + StringBuilder builder = new StringBuilder(path[0]); + + for (int i = 1; i < path.length; i++) { + builder.append(SEP).append(path[i]); + } + + return builder.toString(); + } + } + + public static File createDirectory(File parent, String... path) { + String compactPath = createPath(path); + File file = new File(parent, compactPath); + if (!file.exists() && !file.mkdirs()) { + TLogger.log("Failed to create directory: " + compactPath); + } + + return file; + } + + public static File createFile(File parent, String... path) { + String compactPath = createPath(path); + File file = new File(parent, compactPath); + if (!file.getParentFile().exists() && !file.getParentFile().mkdirs() && !file.getParentFile().exists()) { + TLogger.log("Failed to create file: " + compactPath); + } + + return file; + } + + public static File createFileOrEmpty(File parent, String... path) { + String compactPath = createPath(path); + File file = new File(parent, compactPath); + + try { + if (!file.getParentFile().exists() && !file.getParentFile().mkdirs() || !file.exists() && !file.createNewFile()) { + TLogger.log("Failed to create file: " + compactPath); + } + } catch (IOException var5) { + var5.printStackTrace(); + } + + return file; + } + + public static File createFile(File parent, String scope, ResourceLocation location, String extension) { + File file = new File(parent.getPath() + SEP + location.getNamespace() + SEP + scope, location.getPath() + "." + extension); + if (!file.getParentFile().exists() && !file.getParentFile().mkdirs() && !file.getParentFile().exists()) { + TLogger.log("Failed to create file: " + file.getPath()); + } + + return file; + } + + public static void recreateFile(File file) { + try { + if (!file.getParentFile().exists() && !file.getParentFile().mkdirs() || !file.exists() && !file.createNewFile()) { + TLogger.log("Failed to create file: " + file.getName()); + } + } catch (IOException var2) { + var2.printStackTrace(); + } + } + + public static BufferedImage toImage(String data) { + String[] d = data.split(","); + return d.length > 1 ? rawToImage(d[1]) : rawToImage(data); + } + + public static BufferedImage rawToImage(String data) { + try { + byte[] imageBytes = Base64.getDecoder().decode(data); + return ImageIO.read(new ByteArrayInputStream(imageBytes)); + } catch (IOException var2) { + var2.printStackTrace(); + return null; + } + } + + public static String removeExtension(String path) { + int id = path.lastIndexOf("."); + return id == -1 ? path : path.substring(0, id); + } + + public static boolean isExtension(String path, String extensions) { + int id = path.lastIndexOf("."); + return id == -1 ? false : path.substring(id + 1).equalsIgnoreCase(extensions); + } + + public static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException { + zipFile(fileToZip, fileName, zipOut, true); + } + + public static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut, boolean directoryEntries) throws IOException { + if (!fileToZip.isHidden()) { + if (fileToZip.isDirectory()) { + if (directoryEntries) { + if (fileName.endsWith("/")) { + zipOut.putNextEntry(new ZipEntry(fileName)); + } else { + zipOut.putNextEntry(new ZipEntry(fileName + "/")); + } + + zipOut.closeEntry(); + } + + File[] children = fileToZip.listFiles(); + if (children != null) { + Arrays.sort((Object[])children); + + for (File childFile : children) { + zipFile(childFile, fileName + "/" + childFile.getName(), zipOut, directoryEntries); + } + } + } else { + try (BufferedInputStream fis = new BufferedInputStream(new FileInputStream(fileToZip), 65536)) { + ZipEntry zipEntry = new ZipEntry(fileName); + zipOut.putNextEntry(zipEntry); + byte[] bytes = new byte[65536]; + + int length; + while ((length = fis.read(bytes)) >= 0) { + zipOut.write(bytes, 0, length); + } + } + } + } + } + + public static boolean delete(File file) { + if (!file.isDirectory()) { + return file.delete(); + } else { + File[] list = file.listFiles(); + if (list == null) { + return file.delete(); + } else { + boolean success = true; + + for (File f : list) { + success &= delete(f); + } + + return success & file.delete(); + } + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/callback/Callback.java b/api/src/main/java/com/ticxo/modelengine/api/utils/callback/Callback.java new file mode 100644 index 0000000..2b4b1dd --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/callback/Callback.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.api.utils.callback; + +import com.google.common.collect.Maps; +import java.util.Collection; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; + +public class Callback { + private final Function, T> invoker; + private final Map callbacks = Maps.newConcurrentMap(); + + public Callback(Function, T> invoker) { + this.invoker = invoker; + } + + public UUID subscribe(T callback) { + return this.subscribe(UUID.randomUUID(), callback); + } + + public UUID subscribe(UUID uuid, T callback) { + this.callbacks.put(uuid, callback); + return uuid; + } + + public void unsubscribe(UUID uuid) { + this.callbacks.remove(uuid); + } + + public T invoker() { + return this.invoker.apply(this.callbacks.values()); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigCache.java b/api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigCache.java new file mode 100644 index 0000000..91ce683 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigCache.java @@ -0,0 +1,50 @@ +package com.ticxo.modelengine.api.utils.config; + + +public class ConfigCache { + private boolean emptyZero; + private boolean renderFire; + private boolean eagerGenerate; + private boolean useNewRotation; + private boolean overrideMoveTo; + private String classic; + private String slim; + + public void updateConfig() { + this.emptyZero = ConfigProperty.EMPTY_ZERO.getBoolean(); + this.renderFire = ConfigProperty.RENDER_FIRE.getBoolean(); + this.eagerGenerate = ConfigProperty.EAGER_GENERATE.getBoolean(); + this.useNewRotation = ConfigProperty.USE_NEW_ROTATION.getBoolean(); + this.overrideMoveTo = ConfigProperty.OVERRIDE_MOVE_TO.getBoolean(); + this.classic = ConfigProperty.DEFAULT_CLASSIC_SKIN.getString(); + this.slim = ConfigProperty.DEFAULT_SLIM_SKIN.getString(); + } + + public boolean isEmptyZero() { + return this.emptyZero; + } + + public boolean isRenderFire() { + return this.renderFire; + } + + public boolean isEagerGenerate() { + return this.eagerGenerate; + } + + public boolean isUseNewRotation() { + return this.useNewRotation; + } + + public boolean isOverrideMoveTo() { + return this.overrideMoveTo; + } + + public String getClassic() { + return this.classic; + } + + public String getSlim() { + return this.slim; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigManager.java b/api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigManager.java new file mode 100644 index 0000000..d32ebfe --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigManager.java @@ -0,0 +1,94 @@ +package com.ticxo.modelengine.api.utils.config; + +import com.google.common.collect.Sets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; + +public class ConfigManager { + private final JavaPlugin plugin; + private final Map config = new LinkedHashMap<>(); + private final Set updater = Sets.newConcurrentHashSet(); + private FileConfiguration file; + + public ConfigManager(JavaPlugin plugin) { + this.plugin = plugin; + this.file = plugin.getConfig(); + plugin.saveDefaultConfig(); + } + + public void register(Property property) { + if (property.getDef() != null) { + this.register(property.getPath(), property.getDef()); + } + } + + public void register(String path, @NotNull Object def) { + this.config.put(path, this.file.get(path, def)); + } + + public void registerReferenceUpdate(Runnable runnable) { + this.updater.add(runnable); + runnable.run(); + } + + public void reload() { + this.plugin.reloadConfig(); + this.file = this.plugin.getConfig(); + this.config.replaceAll((p, v) -> this.file.get(p, this.config.get(p))); + } + + public void updateReferences() { + this.updater.forEach(Runnable::run); + } + + public T get(String path) { + try { + return (T)this.config.get(path); + } catch (ClassCastException var3) { + return null; + } + } + + public T get(Property property) { + return this.get(property.getPath()); + } + + public int getInt(Property property) { + return this.get(property); + } + + public double getDouble(Property property) { + return this.get(property) instanceof Number number ? number.doubleValue() : 0.0; + } + + public String getString(Property property) { + return this.get(property); + } + + public boolean getBoolean(Property property) { + return this.get(property); + } + + public List getStringList(Property property) { + return this.get(property); + } + + public ConfigurationSection getConfigSection(String path) { + return this.file.getConfigurationSection(path); + } + + public void set(Property property, Object value) { + this.config.put(property.getPath(), value); + } + + public void save() { + this.config.forEach(this.file::set); + this.plugin.saveConfig(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigProperty.java b/api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigProperty.java new file mode 100644 index 0000000..f88ff8a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/config/ConfigProperty.java @@ -0,0 +1,134 @@ +package com.ticxo.modelengine.api.utils.config; + +import java.util.List; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.MemoryConfiguration; +import org.jetbrains.annotations.Nullable; + +public enum ConfigProperty implements Property { + ENGINE("Model-Engine"), + GENERATOR("Model-Generator"), + OPTIMIZATION("Network-Optimization"), + DEFAULT_NAMES(ENGINE, "Default-Animations"), + SCRIPT_WARNING(ENGINE, "Print-Script-Warnings", false), + USE_STATE_MACHINE(ENGINE, "Use-State-Machine", false), + @Deprecated + ENGINE_THREADS(ENGINE, "Engine-Threads", 4), + MAX_ENGINE_THREADS(ENGINE, "Max-Engine-Threads", 10), + SYNC_CLIENT_TICK_END(ENGINE, "Sync-Client-Tick-End", true), + LOAD_ON_WORLD_LOAD(ENGINE, "Load-On-World-Load", false), + UNLOAD_ON_WORLD_UNLOAD(ENGINE, "Unload-On-World-Unload", false), + MANUAL_TRANSLUCENCY_ORDER(ENGINE, "Manual-Translucency-Order", false), + DEFAULT_PRIORITY(ENGINE, "Default-Animation-Priority", 0), + CLIENT_SYNC_INTERVAL(ENGINE, "Client-Sync-Interval", 60000), + LOWER_SCALE_LIMIT(ENGINE, "Lower-Scale-Limit", 0.001), + FORCE_CMD(ENGINE, "Force-Custom-Model-Data", false), + EMPTY_ZERO(ENGINE, "Process-Empty-Timeline", false), + RENDER_FIRE(ENGINE, "Render-Fire-On-Model", true), + MINESKIN_API_KEY(ENGINE, "MineSkin-API-Key", ""), + USER_LIMB(ENGINE, "User-Limb"), + EAGER_GENERATE(USER_LIMB, "Eager-Generate-Skins", true), + DEFAULT_CLASSIC_SKIN(USER_LIMB, "Default-Classic-Skin", "Steve"), + DEFAULT_SLIM_SKIN(USER_LIMB, "Default-Slim-Skin", "Alex"), + DEFAULT_SKINS(USER_LIMB, "Default-Skins", defaultSkins()), + DELETE_OLD(GENERATOR, "Delete-Old", true), + LATE_REGISTER(GENERATOR, "Register-Post-Server", true), + LATE_ASSETS(GENERATOR, "Assets-Post-Server", true), + LATE_ZIPPING(GENERATOR, "Compile-Post-Server", true), + ERROR(GENERATOR, "Enable-Error", true), + DEBUG_LEVEL(GENERATOR, "Debug-Level", 1), + LOG_ONLY_ERROR(GENERATOR, "Log-Only-Error-Models", false), + NAMESPACE(GENERATOR, "Namespace", "modelengine"), + TEXTURE_PATH(GENERATOR, "Texture-Path", "entity/models"), + ZIP(GENERATOR, "Create-Zip", true), + MERGE_ITEM_MODELS(GENERATOR, "Merge-Item-Models", false), + ATLAS(GENERATOR, "Create-Atlas", true), + SHADER(GENERATOR, "Create-Shader", true), + DISABLED_OVERLAYS(GENERATOR, "Disabled-Overlays", List.of()), + MCMETA(GENERATOR, "Create-MC-META", true), + @Deprecated + ITEM_MODEL(GENERATOR, "Item-Model", "LEATHER_HORSE_ARMOR"), + ITEM_MODELS(GENERATOR, "Item-Models", List.of()), + MAX_GENERATOR_THREADS(GENERATOR, "Max-Generator-Threads", 10), + USE_NEW_ROTATION(GENERATOR, "Use-New-Rotation", false), + BUNDLE_EVERYTHING(OPTIMIZATION, "Bundle-Everything", false), + BUNDLE_SIZE(OPTIMIZATION, "Bundle-Size", 512), + OVERRIDE_MOVE_TO(OPTIMIZATION, "Override-Move-To-Method", true), + CULL_INTERVAL(OPTIMIZATION, "Cull-Interval", 4), + CULLING_THREADS(OPTIMIZATION, "Culling-Threads", 4), + MAX_CULLING_THREADS(OPTIMIZATION, "Max-Culling-Threads", 10), + VERTICAL_CULL(OPTIMIZATION, "Vertical-Render-Distance"), + VERTICAL_CULL_ENABLE(VERTICAL_CULL, "Enabled", true), + VERTICAL_CULL_DISTANCE(VERTICAL_CULL, "Vertical-Render-Distance", 32), + VERTICAL_CULL_TYPE(VERTICAL_CULL, "Cull-Type", "CULLED"), + BACKWARDS_CULL(OPTIMIZATION, "Skip-Models-Behind-Viewer"), + BACKWARDS_CULL_ENABLED(BACKWARDS_CULL, "Enabled", true), + BACKWARDS_CULL_ANGLE(BACKWARDS_CULL, "View-Angle", 180), + BACKWARDS_CULL_IGNORE_RADIUS(BACKWARDS_CULL, "Force-Render-Radius", 5), + BACKWARDS_CULL_TYPE(BACKWARDS_CULL, "Cull-Type", "MOVEMENT_ONLY"), + BLOCK_CULL(OPTIMIZATION, "Skip-Blocked-Models"), + BLOCK_CULL_ENABLE(BLOCK_CULL, "Enabled", true), + BLOCK_CULL_IGNORE_RADIUS(BLOCK_CULL, "Force-Render-Radius", 5), + BLOCK_CULL_TYPE(BLOCK_CULL, "Cull-Type", "CULLED"), + BLOCK_CULL_IGNORE_SIZE(BLOCK_CULL, "Force-Render-Size"), + BLOCK_CULL_USE_PAPER_CLIP(BLOCK_CULL, "Use-Paper-Clip-Method", false), + BLOCK_CULL_IGNORE_SIZE_WIDTH(BLOCK_CULL_IGNORE_SIZE, "Width", 32), + BLOCK_CULL_IGNORE_SIZE_HEIGHT(BLOCK_CULL_IGNORE_SIZE, "Height", 32), + ANIMATION_LOD(OPTIMIZATION, "Reduce-Update-When-Far"), + ANIMATION_LOD_ENABLED(ANIMATION_LOD, "Enabled", true), + ANIMATION_LOD_DEFAULT(ANIMATION_LOD, "Active-By-Default", true), + ANIMATION_LOD_FALLOFF_LENGTH(ANIMATION_LOD, "Falloff-Length", 8), + ANIMATION_LOD_FALLOFF_MULTIPLIER(ANIMATION_LOD, "Falloff-Multiplier", 0.85), + ANIMATION_LOD_IGNORE_DISTANCE(ANIMATION_LOD, "Full-Update-Distance", 16), + ANIMATION_LOD_IGNORE_MULTIPLIER(ANIMATION_LOD, "Full-Update-Distance-Multiplier-By-Size", 1), + ANIMATION_LOD_MAX_RATE_MULTIPLIER(ANIMATION_LOD, "Max-Rate-Multiplier", 1), + ANIMATION_LOD_MIN_RATE_MULTIPLIER(ANIMATION_LOD, "Min-Rate-Multiplier", 0.05); + + private final String path; + private final Object def; + + private ConfigProperty(String path) { + this(path, null); + } + + private ConfigProperty(ConfigProperty scope, String path) { + this(scope.getPath() + "." + path, null); + } + + private ConfigProperty(String path, @Nullable Object def) { + this.path = path; + this.def = def; + } + + private ConfigProperty(ConfigProperty scope, String path, @Nullable Object def) { + this(scope.getPath() + "." + path, def); + } + + private static ConfigurationSection defaultSkins() { + MemoryConfiguration section = new MemoryConfiguration(); + MemoryConfiguration steve = new MemoryConfiguration(); + steve.set( + "base64", + "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAdVBMVEUAAAAKvLwAzMwmGgokGAgrHg0zJBE/KhW3g2uzeV5SPYn///+qclmbY0mQWT8Af38AaGhVVVWUYD52SzOBUzmPXj5JJRBCHQp3QjVqQDA0JRIoKCg3Nzc/Pz9KSko6MYlBNZtGOqUDenoFiIgElZUApKQAr6/wvakZAAAAAXRSTlMAQObYZgAAAolJREFUeNrt1l1rHucZReFrj/whu5hSCCQtlOTE/f+/Jz4q9Cu0YIhLcFVpVg+FsOCVehi8jmZgWOzZz33DM4CXlum3gH95GgeAzQZVeL4gTm6Cbp4vqFkD8HwBazPY8wWbMq9utu3mNZ5fotVezbzOE3kBEFbaZuc8kb00NTMUbWJp678Xf2GV7RRtx1TDQQ6XBNvsmL2+2vHq1TftmMPIyAWujtN2cl274ua2jpVpZneXEjjo7XW1q53V9ds4ODO5xIuhvGHvfLI3aixauig415uuO2+vl9+cncfsFw25zL650fXn687jqnXuP68/X3+eV3zE7y6u9eB73MlfAcfbTf3yR8CfAX+if8S/H5/EAbAxj5LN48tULvEBOh8V1AageMTXe2YHAOwHbZxrzPkSR3+ffr8TR2JDzE/4Fj8CDgEwDsW+q+9GsR07hhg2CsALBgMo2v5wNxXnQXMeGQVW7gUAyKI2m6KDsJ8Au3++F5RZO+kKNQjQcLLWgjwUjBXLltFgWWMUUlviocBgNoxNGgMjSxiYAA7zgLFo2hgIENiDU8gQCzDOmViGFAsEuBcQSDCothhpJaDRA8E5fHqH2nTbYm5fHLo1V0u3B7DAuheoeScRYabjjjuzs17cHVaTrTXmK78m9swP34d9oK/dfeXSIH2PW/MXwPvxN/bJlxw8zlYAcEyeI6gNgA/O8P8neN8xe1IHP2gTzegjvhUDfuRygmwEs2GE4mkCDIAzm2R4yAuPsIdR9k8AvMc+3L9+2UEjo4WP0FpgP19O0MzCsqxIoMsdDBvYcQyGmO0ZJRoYCKjLJWY0BAhYwGUBCgkh8MRdOKt+ruqMwAB2OcEX94U1TPbYJP0PkyyAI1S6cSIAAAAASUVORK5CYII=" + ); + section.set("Steve", steve); + MemoryConfiguration alex = new MemoryConfiguration(); + alex.set( + "base64", + "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAZlBMVEUAAAD////v2r/r0LDvu7HfxKLUt4/zqFiUyJKMvorrmD+GuYTljT97snjegS5xq26UlmuAglpvb29lZWV8Vz51UDhYWFhyTjZPT09sRi5kQSwjYiQrVChcOyc/Pz82NjYYOBYoKCgm8xoJAAAAAXRSTlMAQObYZgAAAwZJREFUeNrtlu1W6jAQRWtjWiaZtCC9/YgC8v4vec9Mg6Uur6b8ve6S0Lo8O2NYmClusOMGF7Nr8HKu2IoDTYPk44K6lvBciePNAm7mlTGz3G2voAaYZg9vFzCCjtnZqoHjAYHDJjAM1tqqgmR7Bahf9tFaA6zND6JwXRpxxosZIkz4uQzOWFmTrJPOUgdjOP1hzu7flmNrJe4wtCBoMgR1LVE1mNIYNbAurpafN5N5Xto8vZbl65PhWg0aRiU/C2Rpa0x5w/LHnjQwZVTgGk755+eyNMbWXDeukQIwMjaRm6qyJjmMtTAi1ziHF0OQQwsul+u1SJBnZsTbRJEgIqzxD8H1erksAt80MLTtCawFpvpScDqtKzhUYpA8yKgAv7Wq4GCripmT4PsKPFGIQxdjbFsPCPiDsbY6tAvBU2K+KRZiCHHquimC0ylGCoH8vjSmVEG4xb0Mmb2MYmGYpgH5boBA7iAIPuxL5CUtT0Q72u0wy6SDioVOosh3k5ggQIZgQB4iDITlOqwoFiaJwzJAcMJARhOShUCX3AGjWMWYYqHv+zghHntwPPaoWQJh58mLRe5FUSpQ6BenWDgi1B81rCAki0oIgiDvQRRlMkh+JdDgi2b78zieEUKEWglRG4gQp+8EEupTeOz78f39/U32n1oKb3iAQ642CWQfPlWAUAr3MtoQ2jck4XmTe7wL7ykPrFkJRkm9HCUuopF8CN6TXsGTEAjvt2+7Gu4Fl/N5xN+PMs6XCwZJLv4BER480MzHFsyfwi9ZpDNSYH7IIKcDPKB4iHSwPk7tVo974ZDYZ1VQ/PKfg9Nsddg6ouWfyCMNh2OqzBbBCdxXUDMq2Cq4r6CmDRVEoRvm4z4Q8OwowdmCbgDThEq8Jwg8pb4gSzANU5cY4l1ngCtDMM0NR4yYwfS5LzgoewXPXwuQ1bZDsIJJ2OJHPvcL49wQJEyGQI+5pV/o9Sj8IKcCSd31C5sFEhrv+gVrzAbBul9QINiwB+t+QdHWLBmyPgXtF8CtX5CO4LsK/gL4WlU0/HKH/gAAAABJRU5ErkJggg==" + ); + alex.set("slim", true); + section.set("Alex", alex); + return section; + } + + @Override + public String getPath() { + return this.path; + } + + @Override + public Object getDef() { + return this.def; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/config/DebugToggle.java b/api/src/main/java/com/ticxo/modelengine/api/utils/config/DebugToggle.java new file mode 100644 index 0000000..1b59821 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/config/DebugToggle.java @@ -0,0 +1,34 @@ +package com.ticxo.modelengine.api.utils.config; + +import java.util.HashSet; +import java.util.Set; +import org.jetbrains.annotations.Nullable; + +public enum DebugToggle { + SHOW_OBB, + SHOW_CULL_POINTS, + NOTIFY_DESYNC; + + private static final Set toggles = new HashSet<>(); + + public static void setDebug(DebugToggle debug, boolean flag) { + if (flag) { + toggles.add(debug); + } else { + toggles.remove(debug); + } + } + + public static boolean isDebugging(DebugToggle debug) { + return toggles.contains(debug); + } + + @Nullable + public static DebugToggle get(String value) { + try { + return valueOf(value); + } catch (Throwable var2) { + return null; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/config/Property.java b/api/src/main/java/com/ticxo/modelengine/api/utils/config/Property.java new file mode 100644 index 0000000..32d1de3 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/config/Property.java @@ -0,0 +1,71 @@ +package com.ticxo.modelengine.api.utils.config; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.generator.BaseItemEnum; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.function.Supplier; +import org.bukkit.configuration.ConfigurationSection; + +public interface Property { + String getPath(); + + Object getDef(); + + default int getInt() { + return ModelEngineAPI.getAPI().getConfigManager().getInt(this); + } + + default int getIntOrIfNeg(Supplier supplier) { + int i = this.getInt(); + return i < 0 ? supplier.get() : i; + } + + default double getDouble() { + return ModelEngineAPI.getAPI().getConfigManager().getDouble(this); + } + + default String getString() { + return ModelEngineAPI.getAPI().getConfigManager().getString(this); + } + + default boolean getBoolean() { + return ModelEngineAPI.getAPI().getConfigManager().getBoolean(this); + } + + default List getStringList() { + return ModelEngineAPI.getAPI().getConfigManager().getStringList(this); + } + + default ConfigurationSection getSection() { + return ModelEngineAPI.getAPI().getConfigManager().getConfigSection(this.getPath()); + } + + default ConfigurationSection getSection(String path) { + return ModelEngineAPI.getAPI().getConfigManager().getConfigSection(this.getPath() + "." + path); + } + + default BaseItemEnum getBaseItem() { + return BaseItemEnum.get(this.getString().toUpperCase(Locale.ENGLISH)); + } + + default Set getBaseItems() { + HashSet set = new HashSet<>(); + + for (String s : this.getStringList()) { + BaseItemEnum item = BaseItemEnum.get(s.toUpperCase(Locale.ENGLISH)); + if (item != null) { + set.add(item); + } + } + + return set; + } + + default CullType getCullType() { + return CullType.get(this.getString().toUpperCase(Locale.ENGLISH)); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/CachedImmutableMap.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/CachedImmutableMap.java new file mode 100644 index 0000000..d27dee2 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/CachedImmutableMap.java @@ -0,0 +1,41 @@ +package com.ticxo.modelengine.api.utils.data; + +import com.google.common.collect.ImmutableMap; +import java.util.Map; +import java.util.function.Supplier; + +public class CachedImmutableMap { + private final Supplier> mapSupplier; + private volatile Map cache; + + public CachedImmutableMap(Map map) { + this(() -> map); + } + + public Map get() { + if (this.cache != null) { + return this.cache; + } else { + synchronized (this) { + if (this.cache != null) { + return this.cache; + } else { + Map supplied = this.mapSupplier.get(); + return this.cache = supplied == null ? ImmutableMap.of() : ImmutableMap.copyOf(supplied); + } + } + } + } + + public Map getIfCached() { + return this.cache; + } + + public void invalidate() { + this.cache = null; + } + + public CachedImmutableMap(Supplier> mapSupplier) { + this.mapSupplier = mapSupplier; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/ComponentUtil.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/ComponentUtil.java new file mode 100644 index 0000000..12677c4 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/ComponentUtil.java @@ -0,0 +1,49 @@ +package com.ticxo.modelengine.api.utils.data; + +import java.util.Set; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.Style; +import net.kyori.adventure.text.format.TextColor; +import net.kyori.adventure.text.format.TextDecoration; +import net.kyori.adventure.text.format.Style.Builder; +import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import net.md_5.bungee.api.chat.BaseComponent; +import org.bukkit.entity.Player; + +public class ComponentUtil { + public static Style reset() { + return ((Builder)Style.style() + .decorations( + Set.of(TextDecoration.BOLD, TextDecoration.ITALIC, TextDecoration.OBFUSCATED, TextDecoration.STRIKETHROUGH, TextDecoration.UNDERLINED), false + )) + .color(NamedTextColor.WHITE) + .build(); + } + + public static Style color(int color) { + return color(TextColor.color(color)); + } + + public static Style color(TextColor color) { + return ((Builder)Style.style() + .decorations( + Set.of(TextDecoration.BOLD, TextDecoration.ITALIC, TextDecoration.OBFUSCATED, TextDecoration.STRIKETHROUGH, TextDecoration.UNDERLINED), false + )) + .color(color) + .build(); + } + + public static String string(Component component) { + return LegacyComponentSerializer.legacySection().serialize(component); + } + + public static BaseComponent[] base(Component component) { + return BungeeComponentSerializer.legacy().serialize(component); + } + + public static void sendMessage(Player player, Component component) { + player.sendMessage(component); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/ConstSet.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/ConstSet.java new file mode 100644 index 0000000..d4c081e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/ConstSet.java @@ -0,0 +1,89 @@ +package com.ticxo.modelengine.api.utils.data; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Set; +import org.jetbrains.annotations.NotNull; + +public class ConstSet implements Set { + private final HashMap map = new HashMap<>(); + + @Override + public int size() { + return this.map.size(); + } + + @Override + public boolean isEmpty() { + return this.map.isEmpty(); + } + + @Override + public boolean contains(Object o) { + return this.map.containsKey(o.hashCode()); + } + + @NotNull + @Override + public Iterator iterator() { + return this.map.values().iterator(); + } + + @NotNull + @Override + public Object[] toArray() { + return this.map.values().toArray(); + } + + @NotNull + @Override + public T1[] toArray(@NotNull T1[] t1s) { + return this.map.values().toArray(t1s); + } + + @Override + public boolean add(T t) { + return this.map.put(t.hashCode(), t) == null; + } + + @Override + public boolean remove(Object o) { + return this.map.remove(o.hashCode()) != null; + } + + @Override + public boolean containsAll(@NotNull Collection collection) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean addAll(@NotNull Collection collection) { + collection.forEach(this::add); + return true; + } + + @Override + public boolean retainAll(@NotNull Collection collection) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean removeAll(@NotNull Collection collection) { + throw new UnsupportedOperationException(); + } + + @Override + public void clear() { + this.map.clear(); + } + + public T fromHash(int hash) { + return this.map.get(hash); + } + + @Override + public String toString() { + return this.map.values().toString(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/GSONUtils.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/GSONUtils.java new file mode 100644 index 0000000..fd07ca4 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/GSONUtils.java @@ -0,0 +1,93 @@ +package com.ticxo.modelengine.api.utils.data; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.UUID; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class GSONUtils { + public static void ifPresent(JsonElement element, String key, Consumer consumer) { + if (element instanceof JsonObject object) { + if (object.has(key)) { + consumer.accept(object.get(key)); + } + } + } + + public static void ifArray(JsonElement element, String key, Consumer forEach) { + if (element instanceof JsonObject object) { + if (object.has(key)) { + if (object.get(key) instanceof JsonArray array) { + array.forEach(forEach); + } + } + } + } + + public static void ifArray(JsonElement element, String key, BiConsumer forEach) { + if (element instanceof JsonObject object) { + if (object.has(key)) { + if (object.get(key) instanceof JsonArray array) { + for (int i = 0; i < array.size(); i++) { + forEach.accept(i, array.get(i)); + } + } + } + } + } + + @Nullable + public static T get(JsonElement element, String key, Function func) { + if (element instanceof JsonObject object) { + if (!object.has(key)) { + return null; + } else { + JsonElement value = object.get(key); + if (value.isJsonNull()) { + return null; + } else { + try { + return func.apply(value); + } catch (Exception var6) { + return null; + } + } + } + } else { + return null; + } + } + + @NotNull + public static T get(JsonElement element, String key, Function func, @NotNull T def) { + T val = get(element, key, func); + return val == null ? def : val; + } + + @NotNull + public static T get(JsonElement element, Function func, @NotNull T def) { + try { + return func.apply(element); + } catch (Exception var4) { + return def; + } + } + + public static Float[] getAsFloatArray(JsonElement jsonElement) { + if (!jsonElement.isJsonArray()) { + return null; + } else { + JsonArray array = jsonElement.getAsJsonArray(); + return array.asList().stream().map(JsonElement::getAsFloat).toArray(Float[]::new); + } + } + + public static UUID getAsUUID(JsonElement jsonElement) { + return UUID.fromString(jsonElement.getAsString()); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/ItemUtils.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/ItemUtils.java new file mode 100644 index 0000000..048b502 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/ItemUtils.java @@ -0,0 +1,134 @@ +package com.ticxo.modelengine.api.utils.data; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collection; +import net.kyori.adventure.text.Component; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.util.Consumer; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +public class ItemUtils { + public static byte[] encodeItemStack(ItemStack item) { + try { + byte[] var3; + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + + try { + dataOutput.writeObject(item); + var3 = outputStream.toByteArray(); + } catch (Throwable var81) { + try { + dataOutput.close(); + } catch (Throwable var7) { + var81.addSuppressed(var7); + } + + throw var81; + } + + dataOutput.close(); + } + + return var3; + } catch (IOException var10) { + throw new RuntimeException(var10); + } + } + + public static String encodeItemStackToString(ItemStack item) { + return encode(encodeItemStack(item)); + } + + public static ItemStack decodeItemStack(byte[] buf) { + try { + ItemStack var3; + try (ByteArrayInputStream inputStream = new ByteArrayInputStream(buf)) { + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + + try { + var3 = (ItemStack)dataInput.readObject(); + } catch (Throwable var81) { + try { + dataInput.close(); + } catch (Throwable var7) { + var81.addSuppressed(var7); + } + + throw var81; + } + + dataInput.close(); + } + + return var3; + } catch (ClassNotFoundException | IOException var10) { + throw new RuntimeException(var10); + } + } + + public static ItemStack decodeItemStack(String data) { + return decodeItemStack(decode(data)); + } + + public static String encode(byte[] buf) { + return Base64.getEncoder().encodeToString(buf); + } + + public static byte[] decode(String src) { + try { + return Base64.getDecoder().decode(src); + } catch (IllegalArgumentException var4) { + try { + return Base64Coder.decodeLines(src); + } catch (Exception var3) { + throw var4; + } + } + } + + public static void name(ItemStack stack, Component component) { + meta(stack, meta -> meta.displayName(component)); + } + + public static void lore(ItemStack stack, Component... components) { + ArrayList list = new ArrayList<>(); + + for (Component component : components) { + if (component != null) { + list.add(component); + } + } + + meta(stack, meta -> meta.lore(list)); + } + + public static void lore(ItemStack stack, Collection components) { + ArrayList list = new ArrayList<>(); + + for (Component component : components) { + if (component != null) { + list.add(component); + } + } + + meta(stack, meta -> meta.lore(list)); + } + + public static void meta(ItemStack stack, Consumer metaConsumer) { + try { + T meta = (T)stack.getItemMeta(); + metaConsumer.accept(meta); + stack.setItemMeta(meta); + } catch (ClassCastException var3) { + var3.printStackTrace(); + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/NullableHashSet.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/NullableHashSet.java new file mode 100644 index 0000000..7e45f7a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/NullableHashSet.java @@ -0,0 +1,10 @@ +package com.ticxo.modelengine.api.utils.data; + +import java.util.LinkedHashSet; + +public class NullableHashSet extends LinkedHashSet { + @Override + public boolean add(T t) { + return t == null ? false : super.add(t); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/PooledCollection.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/PooledCollection.java new file mode 100644 index 0000000..acc7532 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/PooledCollection.java @@ -0,0 +1,88 @@ +package com.ticxo.modelengine.api.utils.data; + +import java.util.HashSet; +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.function.Consumer; +import java.util.function.Supplier; +import org.jetbrains.annotations.Nullable; + +public class PooledCollection { + private final Supplier instanceSupplier; + private final Queue available = new ConcurrentLinkedQueue<>(); + private final Set inUse = ConcurrentHashMap.newKeySet(); + private final Set created = ConcurrentHashMap.newKeySet(); + private final Set released = ConcurrentHashMap.newKeySet(); + + public T getOrCreate() { + T instance = this.available.poll(); + if (instance == null) { + instance = this.instanceSupplier.get(); + this.created.add(instance); + } + + this.inUse.add(instance); + this.released.remove(instance); + return instance; + } + + public void release(T instance) { + if (this.inUse.remove(instance)) { + this.available.add(instance); + this.released.add(instance); + } + } + + public void releaseAll() { + this.released.addAll(this.inUse); + this.released.addAll(this.created); + this.available.addAll(this.inUse); + this.available.addAll(this.created); + this.inUse.clear(); + this.created.clear(); + } + + public Set getAll() { + HashSet set = new HashSet<>(this.available); + set.addAll(this.inUse); + return set; + } + + public void processAll(@Nullable Consumer createdConsumer, @Nullable Consumer oldConsumer, @Nullable Consumer releasedConsumer) { + if (createdConsumer != null || oldConsumer != null) { + for (T t : this.inUse) { + if (this.created.contains(t)) { + if (createdConsumer != null) { + createdConsumer.accept(t); + } + } else if (oldConsumer != null) { + oldConsumer.accept(t); + } + } + } + + if (releasedConsumer != null) { + for (T tx : this.released) { + releasedConsumer.accept(tx); + } + } + } + + public PooledCollection(Supplier instanceSupplier) { + this.instanceSupplier = instanceSupplier; + } + + public Set getInUse() { + return this.inUse; + } + + public Set getCreated() { + return this.created; + } + + public Set getReleased() { + return this.released; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/PositionCodec.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/PositionCodec.java new file mode 100644 index 0000000..14c69ba --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/PositionCodec.java @@ -0,0 +1,69 @@ +package com.ticxo.modelengine.api.utils.data; + +public class PositionCodec { + public static final int RESYNC_INTERVAL = 400; + private long baseX; + private long baseY; + private long baseZ; + private boolean initialized; + private int movesSinceAbsolute; + private short deltaX; + private short deltaY; + private short deltaZ; + + private static long encode(double value) { + return Math.round(value * 4096.0); + } + + public PositionCodec.Result update(double x, double y, double z) { + long nx = encode(x); + long ny = encode(y); + long nz = encode(z); + if (!this.initialized) { + this.initialized = true; + this.baseX = nx; + this.baseY = ny; + this.baseZ = nz; + this.movesSinceAbsolute = 0; + return PositionCodec.Result.ABSOLUTE; + } else { + long dx = nx - this.baseX; + long dy = ny - this.baseY; + long dz = nz - this.baseZ; + if (dx == 0L && dy == 0L && dz == 0L) { + return PositionCodec.Result.UNCHANGED; + } else { + this.baseX = nx; + this.baseY = ny; + this.baseZ = nz; + if (dx == (short)dx && dy == (short)dy && dz == (short)dz && ++this.movesSinceAbsolute < 400) { + this.deltaX = (short)dx; + this.deltaY = (short)dy; + this.deltaZ = (short)dz; + return PositionCodec.Result.MOVE; + } else { + this.movesSinceAbsolute = 0; + return PositionCodec.Result.ABSOLUTE; + } + } + } + } + + public short getDeltaX() { + return this.deltaX; + } + + public short getDeltaY() { + return this.deltaY; + } + + public short getDeltaZ() { + return this.deltaZ; + } + + public static enum Result { + UNCHANGED, + MOVE, + ABSOLUTE; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedAtomic.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedAtomic.java new file mode 100644 index 0000000..bb439b2 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedAtomic.java @@ -0,0 +1,82 @@ +package com.ticxo.modelengine.api.utils.data; + +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public class QueuedAtomic { + private final AtomicReference writer = new AtomicReference<>(); + private final AtomicReference reader = new AtomicReference<>(); + private final BiConsumer> setter; + private final Function, T> getter; + private final BiConsumer, AtomicReference> passer; + + public QueuedAtomic( + Supplier value, + BiConsumer> setter, + Function, T> getter, + BiConsumer, AtomicReference> passer + ) { + this.writer.set(value.get()); + this.reader.set(value.get()); + this.setter = setter; + this.getter = getter; + this.passer = passer; + } + + public void set(T value) { + this.setter.accept(value, this.writer); + } + + public void setUnsafe(T value) { + this.setter.accept(value, this.reader); + } + + public void pass() { + this.passer.accept(this.writer, this.reader); + } + + public T get() { + return this.getter.apply(this.reader); + } + + public T getUnsafe() { + return this.getter.apply(this.writer); + } + + public static QueuedAtomic.Builder builder() { + return new QueuedAtomic.Builder<>(); + } + + public static class Builder { + private Supplier value = () -> null; + private BiConsumer> setter = (val, reference) -> reference.set(val); + private Function, T> getter = AtomicReference::get; + private BiConsumer, AtomicReference> passer = (a, b) -> b.set(a.get()); + + public QueuedAtomic.Builder value(Supplier value) { + this.value = value; + return this; + } + + public QueuedAtomic.Builder setter(BiConsumer> setter) { + this.setter = setter; + return this; + } + + public QueuedAtomic.Builder getter(Function, T> getter) { + this.getter = getter; + return this; + } + + public QueuedAtomic.Builder passer(BiConsumer, AtomicReference> passer) { + this.passer = passer; + return this; + } + + public QueuedAtomic build() { + return new QueuedAtomic<>(this.value, this.setter, this.getter, this.passer); + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedBoolean.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedBoolean.java new file mode 100644 index 0000000..cc50c83 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedBoolean.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.api.utils.data; + +public class QueuedBoolean { + private volatile boolean writer; + private volatile boolean reader; + + public QueuedBoolean(boolean initialValue) { + this.writer = initialValue; + this.reader = initialValue; + } + + public void set(boolean value) { + if (this.writer != value) { + this.writer = value; + } + } + + public void setUnsafe(boolean value) { + this.reader = value; + } + + public void pass() { + this.reader = this.writer; + } + + public boolean get() { + return this.reader; + } + + public boolean getUnsafe() { + return this.writer; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedDouble.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedDouble.java new file mode 100644 index 0000000..f4d6d76 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedDouble.java @@ -0,0 +1,32 @@ +package com.ticxo.modelengine.api.utils.data; + +public class QueuedDouble { + private volatile long writer; + private volatile long reader; + + public QueuedDouble(double initialValue) { + long bits = Double.doubleToRawLongBits(initialValue); + this.writer = bits; + this.reader = bits; + } + + public void set(double value) { + this.writer = Double.doubleToRawLongBits(value); + } + + public void setUnsafe(double value) { + this.reader = Double.doubleToRawLongBits(value); + } + + public void pass() { + this.reader = this.writer; + } + + public double get() { + return Double.longBitsToDouble(this.reader); + } + + public double getUnsafe() { + return Double.longBitsToDouble(this.writer); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedFloat.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedFloat.java new file mode 100644 index 0000000..b327691 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedFloat.java @@ -0,0 +1,35 @@ +package com.ticxo.modelengine.api.utils.data; + +public class QueuedFloat { + private volatile int writer; + private volatile int reader; + + public QueuedFloat(float initialValue) { + int bits = Float.floatToRawIntBits(initialValue); + this.writer = bits; + this.reader = bits; + } + + public void set(float value) { + int bits = Float.floatToRawIntBits(value); + if (this.writer != bits) { + this.writer = bits; + } + } + + public void setUnsafe(float value) { + this.reader = Float.floatToRawIntBits(value); + } + + public void pass() { + this.reader = this.writer; + } + + public float get() { + return Float.intBitsToFloat(this.reader); + } + + public float getUnsafe() { + return Float.intBitsToFloat(this.writer); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedInt.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedInt.java new file mode 100644 index 0000000..77b4206 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/QueuedInt.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.api.utils.data; + +public class QueuedInt { + private volatile int writer; + private volatile int reader; + + public QueuedInt(int initialValue) { + this.writer = initialValue; + this.reader = initialValue; + } + + public void set(int value) { + if (this.writer != value) { + this.writer = value; + } + } + + public void setUnsafe(int value) { + this.reader = value; + } + + public void pass() { + this.reader = this.writer; + } + + public int get() { + return this.reader; + } + + public int getUnsafe() { + return this.writer; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/ResourceLocation.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/ResourceLocation.java new file mode 100644 index 0000000..2e1f8fe --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/ResourceLocation.java @@ -0,0 +1,75 @@ +package com.ticxo.modelengine.api.utils.data; + +import java.util.Locale; + +public class ResourceLocation { + private final String namespace; + private final String path; + + public ResourceLocation(String full) { + full = full.toLowerCase(Locale.ENGLISH); + String[] split = full.split(":", 2); + if (split.length <= 1) { + this.namespace = "minecraft"; + this.path = full; + } else { + this.namespace = split[0]; + this.path = split[1]; + } + } + + @Override + public String toString() { + return !this.namespace.isBlank() && !"minecraft".equals(this.namespace) ? this.namespace + ":" + this.path : this.path; + } + + public boolean isValid() { + return isValidNamespace(this.namespace) && isValidPath(this.path); + } + + public static boolean isValidPath(String path) { + for (int i = 0; i < path.length(); i++) { + if (!validPathChar(path.charAt(i))) { + return false; + } + } + + return true; + } + + public static boolean isValidNamespace(String namespace) { + for (int i = 0; i < namespace.length(); i++) { + if (!validNamespaceChar(namespace.charAt(i))) { + return false; + } + } + + return true; + } + + private static boolean validPathChar(char character) { + return character == '_' + || character == '-' + || character >= 'a' && character <= 'z' + || character >= '0' && character <= '9' + || character == '/' + || character == '.'; + } + + private static boolean validNamespaceChar(char character) { + return character == '_' || character == '-' || character >= 'a' && character <= 'z' || character >= '0' && character <= '9' || character == '.'; + } + + public String getNamespace() { + return this.namespace; + } + + public String getPath() { + return this.path; + } + + public ResourceLocation(String namespace, String path) { + this.namespace = namespace; + this.path = path; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/Triple.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/Triple.java new file mode 100644 index 0000000..a6e3b55 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/Triple.java @@ -0,0 +1,38 @@ +package com.ticxo.modelengine.api.utils.data; + + +public class Triple { + private A first; + private B second; + private C third; + + public A getFirst() { + return this.first; + } + + public B getSecond() { + return this.second; + } + + public C getThird() { + return this.third; + } + + public void setFirst(A first) { + this.first = first; + } + + public void setSecond(B second) { + this.second = second; + } + + public void setThird(C third) { + this.third = third; + } + + public Triple(A first, B second, C third) { + this.first = first; + this.second = second; + this.third = third; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/UpdateScheme.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/UpdateScheme.java new file mode 100644 index 0000000..be24380 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/UpdateScheme.java @@ -0,0 +1,135 @@ +package com.ticxo.modelengine.api.utils.data; + +import java.util.AbstractSet; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.Map.Entry; + +public class UpdateScheme { + private final Map updates = new HashMap<>(); + private final Set added = new UpdateScheme.View(UpdateScheme.Mode.ADD); + private final Set updated = new UpdateScheme.View(UpdateScheme.Mode.UPDATE); + private final Set removed = new UpdateScheme.View(UpdateScheme.Mode.REMOVE); + + public void addUpdated(T element) { + this.updates.compute(element, (k, v) -> (UpdateScheme.Mode)(v == UpdateScheme.Mode.ADD ? v : UpdateScheme.Mode.UPDATE)); + } + + public void addAdded(T element) { + this.updates.put(element, UpdateScheme.Mode.ADD); + } + + public void addRemove(T element) { + this.updates.put(element, UpdateScheme.Mode.REMOVE); + } + + public boolean hasUpdate() { + return !this.updates.isEmpty(); + } + + public UpdateScheme.Mode getUpdateMode(T element) { + UpdateScheme.Mode mode = this.updates.get(element); + return mode == null ? UpdateScheme.Mode.NONE : mode; + } + + public void reset() { + this.updates.clear(); + } + + public Map getUpdates() { + return this.updates; + } + + public Set getAdded() { + return this.added; + } + + public Set getUpdated() { + return this.updated; + } + + public Set getRemoved() { + return this.removed; + } + + public static enum Mode { + NONE, + UPDATE, + ADD, + REMOVE; + } + + private class View extends AbstractSet { + private final UpdateScheme.Mode mode; + + private View(UpdateScheme.Mode mode) { + this.mode = mode; + } + + @Override + public Iterator iterator() { + final Iterator> it = UpdateScheme.this.updates.entrySet().iterator(); + return new Iterator() { + private Entry next; + + @Override + public boolean hasNext() { + while (it.hasNext()) { + this.next = it.next(); + if (this.next.getValue() == View.this.mode) { + return true; + } + } + + return false; + } + + @Override + public T next() { + if (this.next == null) { + throw new NoSuchElementException(); + } else { + return this.next.getKey(); + } + } + }; + } + + @Override + public int size() { + int size = 0; + + for (UpdateScheme.Mode m : UpdateScheme.this.updates.values()) { + if (m == this.mode) { + size++; + } + } + + return size; + } + + @Override + public boolean contains(Object o) { + return UpdateScheme.this.updates.get(o) == this.mode; + } + + @Override + public boolean remove(Object o) { + UpdateScheme.Mode current = UpdateScheme.this.updates.get(o); + if (current == this.mode) { + UpdateScheme.this.updates.remove(o); + return true; + } else { + return false; + } + } + + @Override + public void clear() { + UpdateScheme.this.updates.values().removeIf(m -> m == this.mode); + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/interpolator/BasicInterpolator.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/interpolator/BasicInterpolator.java new file mode 100644 index 0000000..9bfc291 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/interpolator/BasicInterpolator.java @@ -0,0 +1,7 @@ +package com.ticxo.modelengine.api.utils.data.interpolator; + +public class BasicInterpolator extends Interpolator { + public BasicInterpolator() { + this.setParseFunc(value -> value); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/interpolator/Interpolator.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/interpolator/Interpolator.java new file mode 100644 index 0000000..e64bb6f --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/interpolator/Interpolator.java @@ -0,0 +1,75 @@ +package com.ticxo.modelengine.api.utils.data.interpolator; + +import java.util.TreeMap; +import org.jetbrains.annotations.Nullable; + +public class Interpolator extends TreeMap { + protected Interpolator.Interpolation interpolateFunc; + protected Interpolator.Parse parseFunc; + protected OUT defaultValue = (OUT)null; + + public Interpolator setInterpolateFunc(Interpolator.Interpolation interpolateFunc) { + this.interpolateFunc = interpolateFunc; + return this; + } + + public Interpolator setParseFunc(Interpolator.Parse parseFunc) { + this.parseFunc = parseFunc; + return this; + } + + public Interpolator setDefaultValue(OUT value) { + this.defaultValue = value; + return this; + } + + @Nullable + public OUT interpolate(float key) { + if (this.isEmpty()) { + return this.defaultValue; + } else if (this.containsKey(key)) { + return this.parseFunc.parse(this.get(key)); + } else { + float nextKey = this.getHigherKey(key); + float lastKey = this.getLowerKey(key); + if (nextKey == lastKey) { + return this.parseFunc.parse(this.get(lastKey)); + } else { + float t = (key - lastKey) / (nextKey - lastKey); + IN next = this.get(nextKey); + IN prev = this.get(lastKey); + return this.parseFunc.parse(this.interpolateFunc.interpolate(new Interpolator.Context(lastKey, nextKey), prev, next, t)); + } + } + } + + 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 { + public final float prevKey; + public final float nextKey; + + public Context(float prevKey, float nextKey) { + this.prevKey = prevKey; + this.nextKey = nextKey; + } + } + + @FunctionalInterface + public interface Interpolation { + IN interpolate(Interpolator.Context var1, IN var2, IN var3, float var4); + } + + @FunctionalInterface + public interface Parse { + OUT parse(IN var1); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/io/DataIO.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/io/DataIO.java new file mode 100644 index 0000000..8847830 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/io/DataIO.java @@ -0,0 +1,15 @@ +package com.ticxo.modelengine.api.utils.data.io; + +import java.util.Optional; + +public interface DataIO { + default Optional save() { + SavedData data = new SavedData(); + this.save(data); + return data.keySet().isEmpty() ? Optional.empty() : Optional.of(data); + } + + void save(SavedData var1); + + void load(SavedData var1); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/io/SavedData.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/io/SavedData.java new file mode 100644 index 0000000..0a3e22d --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/io/SavedData.java @@ -0,0 +1,247 @@ +package com.ticxo.modelengine.api.utils.data.io; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.utils.data.ItemUtils; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.Supplier; +import org.bukkit.NamespacedKey; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class SavedData extends HashMap { + public static final NamespacedKey DATA_KEY = new NamespacedKey(ModelEngineAPI.getAPI(), "model_data"); + + public static SavedData parse(String json) { + return (SavedData)gson().fromJson(json, SavedData.class); + } + + public void putBoolean(String key, Boolean value) { + this.put(key, value); + } + + public Boolean getBoolean(String key, Boolean def) { + String val = this.getAsString(key); + return val == null ? def : Boolean.parseBoolean(val); + } + + public Boolean getBoolean(String key) { + return this.getBoolean(key, null); + } + + public void putByte(String key, Byte value) { + this.put(key, value); + } + + public Byte getByte(String key, Byte def) { + try { + String val = this.getAsString(key); + return val == null ? def : Byte.parseByte(val); + } catch (NumberFormatException var4) { + this.wrapException(key, var4); + return def; + } + } + + public Byte getByte(String key) { + return this.getByte(key, null); + } + + public void putInt(String key, Integer value) { + this.put(key, value); + } + + public Integer getInt(String key, Integer def) { + try { + String val = this.getAsString(key); + return val == null ? def : (int)Double.parseDouble(val); + } catch (NumberFormatException var4) { + this.wrapException(key, var4); + return def; + } + } + + public Integer getInt(String key) { + return this.getInt(key, null); + } + + public void putFloat(String key, Float value) { + if (value.isNaN() || value.isInfinite()) { + value = 0.0F; + } + + this.put(key, value); + } + + public Float getFloat(String key, Float def) { + try { + String val = this.getAsString(key); + return val == null ? def : Float.parseFloat(val); + } catch (NumberFormatException var4) { + this.wrapException(key, var4); + return def; + } + } + + public Float getFloat(String key) { + return this.getFloat(key, null); + } + + public void putDouble(String key, Double value) { + if (value.isNaN() || value.isInfinite()) { + value = 0.0; + } + + this.put(key, value); + } + + public Double getDouble(String key, Double def) { + try { + String val = this.getAsString(key); + return val == null ? def : Double.parseDouble(val); + } catch (NumberFormatException var4) { + this.wrapException(key, var4); + return def; + } + } + + public Double getDouble(String key) { + return this.getDouble(key, null); + } + + public void putString(String key, String value) { + this.put(key, value); + } + + public String getString(String key, String def) { + return this.getOrDefaultAsString(key, def); + } + + public String getString(String key) { + return this.getString(key, null); + } + + public void putUUID(String key, UUID value) { + this.put(key, value); + } + + public UUID getUUID(String key, UUID def) { + String value = this.getAsString(key); + return value == null ? def : UUID.fromString(value); + } + + public UUID getUUID(String key) { + return this.getUUID(key, null); + } + + public void putList(String key, Collection collection) { + this.put(key, collection); + } + + public List getList(String key) { + String value = this.getAsString(key); + return value == null ? List.of() : (List)gson().fromJson(value, (new TypeToken() {}).getType()); + } + + public List getList(String key, Class clazz) { + String value = gson().toJson(this.get(key)); + return value == null ? List.of() : (List)gson().fromJson(value, TypeToken.getParameterized(List.class, new Type[]{clazz})); + } + + public void putData(String key, SavedData value) { + if (this == value) { + throw new RuntimeException("Cannot add data: Attempting to add self to self."); + } else { + this.put(key, value); + } + } + + public Optional getData(String key) { + Object value = this.get(key); + if (value instanceof Map) { + SavedData data = new SavedData(); + data.putAll((Map)value); + return Optional.of(data); + } else { + return Optional.empty(); + } + } + + public void putItemStack(String key, @Nullable ItemStack stack) { + if (stack != null) { + this.putString(key, ItemUtils.encodeItemStackToString(stack)); + } + } + + public ItemStack getItemStack(String key) { + return this.getItemStack(key, null); + } + + public ItemStack getItemStack(String key, ItemStack def) { + String value = this.getAsString(key); + if (value == null) { + return def; + } else { + try { + return ItemUtils.decodeItemStack(value); + } catch (Throwable var5) { + var5.printStackTrace(); + return def; + } + } + } + + public void saveIfExist(String key, Supplier supplier, SavedData.DataSaver saveConsumer) { + T val = supplier.get(); + if (val != null) { + saveConsumer.save(this, key, val); + } + } + + public void loadIfExist(String key, SavedData.DataLoader getter, Consumer consumer) { + T val = getter.load(this, key); + if (val != null) { + consumer.accept(val); + } + } + + @Override + public String toString() { + return gson().toJson(this); + } + + private void wrapException(String key, Exception e) { + throw new RuntimeException("An error occurred while reading the value of " + key, e); + } + + private String getAsString(String key) { + return this.getOrDefaultAsString(key, null); + } + + private String getOrDefaultAsString(String key, String def) { + Object obj = this.get(key); + return obj == null ? def : obj.toString(); + } + + private static Gson gson() { + return ModelEngineAPI.getAPI().getGson(); + } + + @FunctionalInterface + public interface DataLoader { + S load(SavedData var1, String var2); + } + + @FunctionalInterface + public interface DataSaver { + void save(SavedData var1, String var2, S var3); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/CollectionDataTracker.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/CollectionDataTracker.java new file mode 100644 index 0000000..24ae7b4 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/CollectionDataTracker.java @@ -0,0 +1,92 @@ +package com.ticxo.modelengine.api.utils.data.tracker; + +import java.util.Collection; +import java.util.Iterator; +import org.jetbrains.annotations.NotNull; + +public class CollectionDataTracker extends DataTracker> implements Collection { + public CollectionDataTracker(Collection value) { + super(value); + } + + @Override + public int size() { + return this.value.size(); + } + + @Override + public boolean isEmpty() { + return this.value.isEmpty(); + } + + @Override + public boolean contains(Object o) { + return this.value.contains(o); + } + + @NotNull + @Override + public Iterator iterator() { + return this.value.iterator(); + } + + @NotNull + @Override + public Object[] toArray() { + return this.value.toArray(); + } + + @NotNull + @Override + public T1[] toArray(@NotNull T1[] a) { + return this.value.toArray(a); + } + + @Override + public boolean add(T t) { + boolean flag = this.value.add(t); + this.isDirty |= flag; + return flag; + } + + @Override + public boolean remove(Object o) { + boolean flag = this.value.remove(o); + this.isDirty |= flag; + return flag; + } + + @Override + public boolean containsAll(@NotNull Collection c) { + return this.value.containsAll(c); + } + + @Override + public boolean addAll(@NotNull Collection c) { + boolean flag = this.value.addAll(c); + this.isDirty |= flag; + return flag; + } + + @Override + public boolean removeAll(@NotNull Collection c) { + boolean flag = this.value.removeAll(c); + this.isDirty |= flag; + return flag; + } + + @Override + public boolean retainAll(@NotNull Collection c) { + boolean flag = this.value.retainAll(c); + this.isDirty |= flag; + return flag; + } + + @Override + public void clear() { + if (!this.value.isEmpty()) { + this.value.clear(); + this.isDirty = true; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/DataTracker.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/DataTracker.java new file mode 100644 index 0000000..20d9853 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/DataTracker.java @@ -0,0 +1,70 @@ +package com.ticxo.modelengine.api.utils.data.tracker; + +import java.util.Objects; +import java.util.function.BiPredicate; +import java.util.function.Consumer; + +public class DataTracker { + protected final BiPredicate equal; + protected boolean isDirty; + protected T value; + + public DataTracker() { + this.equal = Object::equals; + } + + public DataTracker(T value) { + this(value, Objects::equals); + } + + public DataTracker(BiPredicate equal) { + this(null, equal); + } + + public DataTracker(T value, BiPredicate equal) { + this.value = value; + this.equal = equal; + } + + public void markDirty() { + this.isDirty = true; + } + + public void clearDirty() { + this.isDirty = false; + } + + public void ifDirty(Consumer consumer) { + if (this.isDirty) { + consumer.accept(this.get()); + } + } + + public void ifDirty(Consumer consumer, boolean force) { + if (this.isDirty || force) { + consumer.accept(this.get()); + } + } + + public void set(T value) { + this.set(value, null); + } + + public void set(T value, Runnable ifDirty) { + if (this.value == null || !this.equal.test(this.value, value)) { + this.value = value; + this.isDirty = true; + if (ifDirty != null) { + ifDirty.run(); + } + } + } + + public T get() { + return this.value; + } + + public boolean isDirty() { + return this.isDirty; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/FloatDataTracker.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/FloatDataTracker.java new file mode 100644 index 0000000..198d9da --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/FloatDataTracker.java @@ -0,0 +1,29 @@ +package com.ticxo.modelengine.api.utils.data.tracker; + +public class FloatDataTracker { + private float value; + private boolean isDirty; + + public FloatDataTracker(float initialValue) { + this.value = initialValue; + } + + public void set(float value) { + if (!(Math.abs(value - this.value) < 1.0E-5F)) { + this.value = value; + this.isDirty = true; + } + } + + public float get() { + return this.value; + } + + public boolean isDirty() { + return this.isDirty; + } + + public void clearDirty() { + this.isDirty = false; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/MapDataTracker.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/MapDataTracker.java new file mode 100644 index 0000000..b001d28 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/MapDataTracker.java @@ -0,0 +1,108 @@ +package com.ticxo.modelengine.api.utils.data.tracker; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class MapDataTracker extends DataTracker> implements Map { + public MapDataTracker(Map value) { + super(value); + } + + public void set(Map map, Runnable ifDirty) { + if (this.value != map && (map == null || !this.value.isEmpty() || !map.isEmpty()) && !this.equal.test(this.value, map)) { + this.isDirty = true; + this.value.clear(); + this.value.putAll(map); + if (ifDirty != null) { + ifDirty.run(); + } + } + } + + @Override + public int size() { + return this.value.size(); + } + + @Override + public boolean isEmpty() { + return this.value.isEmpty(); + } + + @Override + public boolean containsKey(Object key) { + return this.value.containsKey(key); + } + + @Override + public boolean containsValue(Object value) { + return this.value.containsValue(value); + } + + @Override + public U get(Object key) { + return this.value.get(key); + } + + @Nullable + @Override + public U put(T key, U value) { + U prev = this.value.put(key, value); + this.isDirty |= prev != value; + return prev; + } + + @Override + public U remove(Object key) { + if (!this.isDirty) { + this.isDirty = this.value.containsKey(key); + } + + return this.value.remove(key); + } + + @Override + public void putAll(@NotNull Map m) { + if (!this.isDirty) { + for (Entry entry : m.entrySet()) { + U t = this.value.get(entry.getKey()); + if (t == null || t != entry.getValue()) { + this.isDirty = true; + break; + } + } + } + + this.value.putAll(m); + } + + @Override + public void clear() { + if (!this.value.isEmpty()) { + this.value.clear(); + this.isDirty = true; + } + } + + @NotNull + @Override + public Set keySet() { + return this.value.keySet(); + } + + @NotNull + @Override + public Collection values() { + return this.value.values(); + } + + @NotNull + @Override + public Set> entrySet() { + return this.value.entrySet(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/QuaternionfDataTracker.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/QuaternionfDataTracker.java new file mode 100644 index 0000000..97dbb7d --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/QuaternionfDataTracker.java @@ -0,0 +1,32 @@ +package com.ticxo.modelengine.api.utils.data.tracker; + +import com.ticxo.modelengine.api.utils.math.TMath; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; + +public final class QuaternionfDataTracker extends DataTracker { + public QuaternionfDataTracker() { + super(new Quaternionf()); + } + + public void set(Quaternionf value) { + if (this.value == null || !TMath.isSimilar(this.value, value)) { + this.value.set(value); + this.isDirty = true; + } + } + + public void set(Quaternionf value, Runnable ifDirty) { + if (this.value == null || !TMath.isSimilar(this.value, value)) { + this.value.set(value); + this.isDirty = true; + if (ifDirty != null) { + ifDirty.run(); + } + } + } + + public Quaternionf get() { + return new Quaternionf((Quaternionfc)this.value); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/UpdateDataTracker.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/UpdateDataTracker.java new file mode 100644 index 0000000..8cdf58e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/UpdateDataTracker.java @@ -0,0 +1,60 @@ +package com.ticxo.modelengine.api.utils.data.tracker; + +import java.util.Objects; +import java.util.function.BiConsumer; +import java.util.function.BiPredicate; +import java.util.function.Function; + +public class UpdateDataTracker extends DataTracker { + private final BiConsumer setter; + private final Function supplier; + private final BiPredicate comparer; + + public UpdateDataTracker(BiConsumer setter) { + this.setter = setter; + this.supplier = t -> t; + this.comparer = Objects::equals; + } + + public UpdateDataTracker(T value, BiConsumer setter) { + super(value); + this.setter = setter; + this.supplier = t -> t; + this.comparer = Objects::equals; + } + + public UpdateDataTracker(T value, BiConsumer setter, Function supplier) { + super(value); + this.setter = setter; + this.supplier = supplier; + this.comparer = Objects::equals; + } + + public UpdateDataTracker(T value, BiConsumer setter, Function supplier, BiPredicate comparer) { + super(value); + this.setter = setter; + this.supplier = supplier; + this.comparer = comparer; + } + + @Override + public void set(T value) { + this.set(value, null); + } + + @Override + public void set(T value, Runnable ifDirty) { + if (this.value == null || !this.comparer.test(this.value, value)) { + this.setter.accept(this.value, value); + this.isDirty = true; + if (ifDirty != null) { + ifDirty.run(); + } + } + } + + @Override + public T get() { + return this.supplier.apply(this.value); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/Vector3fDataTracker.java b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/Vector3fDataTracker.java new file mode 100644 index 0000000..020eb95 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/data/tracker/Vector3fDataTracker.java @@ -0,0 +1,32 @@ +package com.ticxo.modelengine.api.utils.data.tracker; + +import com.ticxo.modelengine.api.utils.math.TMath; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public final class Vector3fDataTracker extends DataTracker { + public Vector3fDataTracker() { + super(new Vector3f()); + } + + public void set(Vector3f value) { + if (this.value == null || !TMath.isSimilar(this.value, value)) { + this.value.set(value); + this.isDirty = true; + } + } + + public void set(Vector3f value, Runnable ifDirty) { + if (this.value == null || !TMath.isSimilar(this.value, value)) { + this.value.set(value); + this.isDirty = true; + if (ifDirty != null) { + ifDirty.run(); + } + } + } + + public Vector3f get() { + return new Vector3f((Vector3fc)this.value); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/logger/LogColor.java b/api/src/main/java/com/ticxo/modelengine/api/utils/logger/LogColor.java new file mode 100644 index 0000000..8289eda --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/logger/LogColor.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.api.utils.logger; + + +public enum LogColor { + BLACK("\u001b[30m"), + RED("\u001b[31m"), + GREEN("\u001b[32m"), + YELLOW("\u001b[33m"), + BLUE("\u001b[34m"), + PURPLE("\u001b[35m"), + CYAN("\u001b[36m"), + WHITE("\u001b[37m"), + BRIGHT_GREEN("\u001b[38;5;46m"), + RESET("\u001b[0m"), + BOLD("\u001b[1m"), + ITALICS("\u001b[2m"), + UNDERLINE("\u001b[4m"); + + private final String ansiColor; + + private LogColor(String ansiColor) { + this.ansiColor = ansiColor; + } + + @Override + public String toString() { + return this.ansiColor; + } + + public String getAnsiColor() { + return this.ansiColor; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/logger/TLogger.java b/api/src/main/java/com/ticxo/modelengine/api/utils/logger/TLogger.java new file mode 100644 index 0000000..14d63b0 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/logger/TLogger.java @@ -0,0 +1,172 @@ +package com.ticxo.modelengine.api.utils.logger; + +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.Objects; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.Bukkit; + +public class TLogger { + public static Logger logger; + + public static void log() { + log(""); + } + + public static void log(String string) { + log(1, string); + } + + public static void log(int level, String string) { + if (ConfigProperty.DEBUG_LEVEL.getInt() >= level) { + logger.log(Level.INFO, getThread() + string + LogColor.RESET); + } + } + + public static void log(Object object) { + log(object == null ? "null" : object.toString()); + } + + public static void log(Iterable iterable) { + log(1, iterable); + } + + public static void log(Iterable iterable, Function toString) { + log(1, iterable, toString); + } + + public static void log(int level, Iterable iterable) { + log(level, iterable, Object::toString); + } + + public static void log(int level, Iterable iterable, Function toString) { + String className = iterable.getClass().getSimpleName(); + StringBuilder builder = new StringBuilder(); + builder.append(className).append(":["); + boolean isFirst = true; + + for (T value : iterable) { + if (!isFirst) { + builder.append(", "); + } else { + isFirst = false; + } + + builder.append(toString.apply(value)); + } + + builder.append("]"); + log(level, builder.toString()); + } + + public static void log(T[] array) { + log(1, array); + } + + public static void log(T[] array, Function toString) { + log(1, array, toString); + } + + public static void log(int level, T[] array) { + log(level, array, Objects::toString); + } + + public static void log(int level, T[] array, Function toString) { + String className = array.getClass().getSimpleName(); + StringBuilder builder = new StringBuilder(); + builder.append(className).append(":["); + boolean isFirst = true; + + for (T value : array) { + if (!isFirst) { + builder.append(", "); + } else { + isFirst = false; + } + + builder.append(toString.apply(value)); + } + + builder.append("]"); + log(level, builder.toString()); + } + + public static void stacktrace() { + if (isDebugEnabled()) { + log(Thread.currentThread().getStackTrace(), stackTraceElement -> "\n" + stackTraceElement); + } + } + + public static void debug() { + if (isDebugEnabled()) { + log(); + } + } + + public static void debug(String string) { + if (isDebugEnabled()) { + log(string); + } + } + + public static void debug(int level, String string) { + if (isDebugEnabled()) { + log(level, string); + } + } + + public static void debug(Object object) { + if (isDebugEnabled()) { + log(object); + } + } + + public static void debug(Iterable iterable) { + debug(iterable, Objects::toString); + } + + public static void debug(Iterable iterable, Function toString) { + if (isDebugEnabled()) { + log(iterable, toString); + } + } + + public static void debug(T[] array) { + debug(array, Objects::toString); + } + + public static void debug(T[] array, Function toString) { + if (isDebugEnabled()) { + log(array, toString); + } + } + + private static boolean isDebugEnabled() { + return ConfigProperty.DEBUG_LEVEL.getInt() == 157; + } + + public static void warn(String string) { + warn(1, string); + } + + public static void warn(int level, String string) { + if (ConfigProperty.DEBUG_LEVEL.getInt() >= level) { + logger.log(Level.WARNING, getThread() + LogColor.YELLOW + string + LogColor.RESET); + } + } + + public static void error(String string) { + error(1, string); + } + + public static void error(int level, String string) { + if (ConfigProperty.DEBUG_LEVEL.getInt() >= level) { + logger.log(Level.WARNING, getThread() + LogColor.RED + string + LogColor.RESET); + } + } + + private static String getThread() { + return Bukkit.getServer().isPrimaryThread() ? "[S] " : "[A] "; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/math/Axis.java b/api/src/main/java/com/ticxo/modelengine/api/utils/math/Axis.java new file mode 100644 index 0000000..af159b5 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/math/Axis.java @@ -0,0 +1,19 @@ +package com.ticxo.modelengine.api.utils.math; + +import org.joml.Vector3d; + +public enum Axis { + X(new Vector3d(1.0, 0.0, 0.0)), + Y(new Vector3d(0.0, 1.0, 0.0)), + Z(new Vector3d(0.0, 0.0, 1.0)); + + private final Vector3d vector; + + public Vector3d getVector() { + return this.vector.get(new Vector3d()); + } + + private Axis(Vector3d vector) { + this.vector = vector; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/math/Box.java b/api/src/main/java/com/ticxo/modelengine/api/utils/math/Box.java new file mode 100644 index 0000000..b4ef006 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/math/Box.java @@ -0,0 +1,10 @@ +package com.ticxo.modelengine.api.utils.math; + +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; + +public interface Box { + @NotNull + BoundingBox createBoundingBox(Vector var1); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/math/ColorHelper.java b/api/src/main/java/com/ticxo/modelengine/api/utils/math/ColorHelper.java new file mode 100644 index 0000000..ac5171f --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/math/ColorHelper.java @@ -0,0 +1,162 @@ +package com.ticxo.modelengine.api.utils.math; + + +public class ColorHelper { + public static int getAlpha(int argb) { + return argb >>> 24; + } + + public static int getRed(int argb) { + return argb >> 16 & 0xFF; + } + + public static int getGreen(int argb) { + return argb >> 8 & 0xFF; + } + + public static int getBlue(int argb) { + return argb & 0xFF; + } + + public static int getArgb(int alpha, int red, int green, int blue) { + return alpha << 24 | red << 16 | green << 8 | blue; + } + + public static int getArgbFloat(float alpha, float red, float green, float blue) { + return getArgb( + TMath.floor(TMath.clamp(alpha * 255.0F, 0.0F, 1.0F)), + TMath.floor(TMath.clamp(red * 255.0F, 0.0F, 1.0F)), + TMath.floor(TMath.clamp(green * 255.0F, 0.0F, 1.0F)), + TMath.floor(TMath.clamp(blue * 255.0F, 0.0F, 1.0F)) + ); + } + + public static ColorHelper.HSL toHSL(int color) { + return toHSL(getAlpha(color), getRed(color), getGreen(color), getBlue(color)); + } + + public static ColorHelper.HSL toHSL(int alpha, int red, int green, int blue) { + ColorHelper.HSL color = new ColorHelper.HSL(); + color.alpha = alpha; + float r = red / 255.0F; + float g = green / 255.0F; + float b = blue / 255.0F; + float cMax = Math.max(r, Math.max(g, b)); + float cMin = Math.min(r, Math.min(g, b)); + float delta = cMax - cMin; + color.lightness = (cMax + cMin) * 0.5F; + if (Math.abs(delta) <= 1.0E-5F) { + color.hue = 0.0F; + color.saturation = 0.0F; + } else { + if (cMax != r) { + if (cMax == g) { + color.hue = 60.0F * ((b - r) / delta + 2.0F); + } else if (cMax == b) { + color.hue = 60.0F * ((r - g) / delta + 4.0F); + } + } else { + float f = (g - b) / delta; + + while (f < 0.0F) { + f += 6.0F; + } + + color.hue = 60.0F * (f % 6.0F); + } + + color.saturation = delta / (1.0F - Math.abs(2.0F * color.lightness - 1.0F)); + } + + color.sanitize(); + return color; + } + + public static int fromHSL(ColorHelper.HSL hsl) { + hsl.sanitize(); + float c = (1.0F - Math.abs(2.0F * hsl.lightness - 1.0F)) * hsl.saturation; + float x = c * (1.0F - Math.abs(hsl.hue / 60.0F % 2.0F - 1.0F)); + float m = hsl.lightness - c * 0.5F; + float r = 0.0F; + float g = 0.0F; + float b = 0.0F; + switch ((int)hsl.hue / 60 % 6) { + case 0: + r = c; + g = x; + break; + case 1: + r = x; + g = c; + break; + case 2: + g = c; + b = x; + break; + case 3: + g = x; + b = c; + break; + case 4: + r = x; + b = c; + break; + case 5: + r = c; + b = x; + } + + return getArgb(hsl.alpha, TMath.floor((r + m) * 255.0F), TMath.floor((g + m) * 255.0F), TMath.floor((b + m) * 255.0F)); + } + + public static int mixColor(int first, int second) { + return getArgb( + getAlpha(first) * getAlpha(second) / 255, + getRed(first) * getRed(second) / 255, + getGreen(first) * getGreen(second) / 255, + getBlue(first) * getBlue(second) / 255 + ); + } + + public static int lerpColor(int colorA, int colorB, float ratio) { + int aA = getAlpha(colorA); + int aR = getRed(colorA); + int aG = getGreen(colorA); + int aB = getBlue(colorA); + int bA = getAlpha(colorB); + int bR = getRed(colorB); + int bG = getGreen(colorB); + int bB = getBlue(colorB); + int fA = TMath.floor(Math.sqrt(TMath.lerp((float)(aA * aA), (float)(bA * bA), ratio))); + int fR = TMath.floor(Math.sqrt(TMath.lerp((float)(aR * aR), (float)(bR * bR), ratio))); + int fG = TMath.floor(Math.sqrt(TMath.lerp((float)(aG * aG), (float)(bG * bG), ratio))); + int fB = TMath.floor(Math.sqrt(TMath.lerp((float)(aB * aB), (float)(bB * bB), ratio))); + return getArgb(fA, fR, fG, fB); + } + + public static class HSL { + public int alpha; + public float hue; + public float saturation; + public float lightness; + + public HSL() { + } + + public void sanitize() { + while (this.hue < 0.0F) { + this.hue += 360.0F; + } + + this.saturation = Math.max(Math.min(this.saturation, 1.0F), 0.0F); + this.lightness = Math.max(Math.min(this.lightness, 1.0F), 0.0F); + } + + public HSL(int alpha, float hue, float saturation, float lightness) { + this.alpha = alpha; + this.hue = hue; + this.saturation = saturation; + this.lightness = lightness; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/math/Direction.java b/api/src/main/java/com/ticxo/modelengine/api/utils/math/Direction.java new file mode 100644 index 0000000..5b27704 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/math/Direction.java @@ -0,0 +1,38 @@ +package com.ticxo.modelengine.api.utils.math; + +import org.joml.Vector3d; + +public enum Direction { + NORTH(new Vector3d(0.0, 0.0, -1.0), new Vector3d(0.0, 1.0, 0.0).normalize()), + EAST(new Vector3d(1.0, 0.0, 0.0), new Vector3d(0.0, 1.0, 0.0).normalize()), + SOUTH(new Vector3d(0.0, 0.0, 1.0), new Vector3d(0.0, 1.0, 0.0).normalize()), + WEST(new Vector3d(-1.0, 0.0, 0.0), new Vector3d(0.0, 1.0, 0.0).normalize()), + UP(new Vector3d(0.0, 1.0, 0.0), new Vector3d(0.0, 0.0, -1.0).normalize()), + DOWN(new Vector3d(0.0, -1.0, 0.0), new Vector3d(0.0, 0.0, 1.0).normalize()); + + private final Vector3d normal; + private final Vector3d uvUp; + + public Vector3d getNormal() { + return new Vector3d(this.normal); + } + + public Vector3d getUvUp() { + return new Vector3d(this.uvUp); + } + + public static Direction fromNormal(Vector3d normal) { + for (Direction value : values()) { + if (TMath.isSimilar(value.normal.dot(normal), 1.0)) { + return value; + } + } + + return null; + } + + private Direction(Vector3d normal, Vector3d uvUp) { + this.normal = normal; + this.uvUp = uvUp; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/math/Easing.java b/api/src/main/java/com/ticxo/modelengine/api/utils/math/Easing.java new file mode 100644 index 0000000..660bb76 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/math/Easing.java @@ -0,0 +1,163 @@ +package com.ticxo.modelengine.api.utils.math; + +import java.util.Locale; +import java.util.function.DoubleUnaryOperator; +import java.util.regex.Pattern; +import org.jetbrains.annotations.Nullable; + +public enum Easing { + LINEAR(Easing.Fn.LINEAR), + EASE_IN_SINE(Easing.Fn.IN_SINE), + EASE_OUT_SINE(Easing.Fn.OUT_SINE), + EASE_IN_OUT_SINE(Easing.Fn.IN_OUT_SINE), + EASE_IN_QUAD(Easing.Fn.IN_QUAD), + EASE_OUT_QUAD(Easing.Fn.OUT_QUAD), + EASE_IN_OUT_QUAD(Easing.Fn.IN_OUT_QUAD), + EASE_IN_CUBIC(Easing.Fn.IN_CUBIC), + EASE_OUT_CUBIC(Easing.Fn.OUT_CUBIC), + EASE_IN_OUT_CUBIC(Easing.Fn.IN_OUT_CUBIC), + EASE_IN_QUART(Easing.Fn.IN_QUART), + EASE_OUT_QUART(Easing.Fn.OUT_QUART), + EASE_IN_OUT_QUART(Easing.Fn.IN_OUT_QUART), + EASE_IN_QUINT(Easing.Fn.IN_QUINT), + EASE_OUT_QUINT(Easing.Fn.OUT_QUINT), + EASE_IN_OUT_QUINT(Easing.Fn.IN_OUT_QUINT), + EASE_IN_EXPO(Easing.Fn.IN_EXPO), + EASE_OUT_EXPO(Easing.Fn.OUT_EXPO), + EASE_IN_OUT_EXPO(Easing.Fn.IN_OUT_EXPO), + EASE_IN_CIRC(Easing.Fn.IN_CIRC), + EASE_OUT_CIRC(Easing.Fn.OUT_CIRC), + EASE_IN_OUT_CIRC(Easing.Fn.IN_OUT_CIRC), + EASE_IN_BACK(Easing.Fn.IN_BACK), + EASE_OUT_BACK(Easing.Fn.OUT_BACK), + EASE_IN_OUT_BACK(Easing.Fn.IN_OUT_BACK), + EASE_IN_ELASTIC(Easing.Fn.IN_ELASTIC), + EASE_OUT_ELASTIC(Easing.Fn.OUT_ELASTIC), + EASE_IN_OUT_ELASTIC(Easing.Fn.IN_OUT_ELASTIC), + EASE_IN_BOUNCE(Easing.Fn.IN_BOUNCE), + EASE_OUT_BOUNCE(Easing.Fn.OUT_BOUNCE), + EASE_IN_OUT_BOUNCE(Easing.Fn.IN_OUT_BOUNCE); + + private static final Pattern CAMEL_BOUNDARY = Pattern.compile("([a-z])([A-Z])"); + private final DoubleUnaryOperator function; + + public double apply(double t) { + return this.function.applyAsDouble(t); + } + + public static Easing get(String name) { + Easing easing = getOrNull(name); + return easing == null ? LINEAR : easing; + } + + @Nullable + public static Easing getOrNull(String name) { + if (name == null) { + return null; + } else { + try { + return valueOf(normalize(name)); + } catch (IllegalArgumentException var2) { + return null; + } + } + } + + private static String normalize(String name) { + return CAMEL_BOUNDARY.matcher(name.trim().replace('-', '_')).replaceAll("$1_$2").toUpperCase(Locale.ENGLISH); + } + + private Easing(DoubleUnaryOperator function) { + this.function = function; + } + + private static class Fn { + private static final double C1 = 1.70158; + private static final double C2 = 2.5949095; + private static final double C3 = 2.70158; + private static final double C4 = Math.PI * 2.0 / 3.0; + private static final double C5 = Math.PI * 4.0 / 9.0; + private static final double N1 = 7.5625; + private static final double D1 = 2.75; + private static final DoubleUnaryOperator LINEAR = x -> x; + private static final DoubleUnaryOperator IN_SINE = x -> 1.0 - Math.cos(x * Math.PI / 2.0); + private static final DoubleUnaryOperator OUT_SINE = x -> Math.sin(x * Math.PI / 2.0); + private static final DoubleUnaryOperator IN_OUT_SINE = x -> -(Math.cos(Math.PI * x) - 1.0) / 2.0; + private static final DoubleUnaryOperator IN_QUAD = x -> x * x; + private static final DoubleUnaryOperator OUT_QUAD = x -> 1.0 - (1.0 - x) * (1.0 - x); + private static final DoubleUnaryOperator IN_OUT_QUAD = x -> x < 0.5 ? 2.0 * x * x : 1.0 - Math.pow(-2.0 * x + 2.0, 2.0) / 2.0; + private static final DoubleUnaryOperator IN_CUBIC = x -> x * x * x; + private static final DoubleUnaryOperator OUT_CUBIC = x -> 1.0 - Math.pow(1.0 - x, 3.0); + private static final DoubleUnaryOperator IN_OUT_CUBIC = x -> x < 0.5 ? 4.0 * x * x * x : 1.0 - Math.pow(-2.0 * x + 2.0, 3.0) / 2.0; + private static final DoubleUnaryOperator IN_QUART = x -> x * x * x * x; + private static final DoubleUnaryOperator OUT_QUART = x -> 1.0 - Math.pow(1.0 - x, 4.0); + private static final DoubleUnaryOperator IN_OUT_QUART = x -> x < 0.5 ? 8.0 * x * x * x * x : 1.0 - Math.pow(-2.0 * x + 2.0, 4.0) / 2.0; + private static final DoubleUnaryOperator IN_QUINT = x -> x * x * x * x * x; + private static final DoubleUnaryOperator OUT_QUINT = x -> 1.0 - Math.pow(1.0 - x, 5.0); + private static final DoubleUnaryOperator IN_OUT_QUINT = x -> x < 0.5 ? 16.0 * x * x * x * x * x : 1.0 - Math.pow(-2.0 * x + 2.0, 5.0) / 2.0; + private static final DoubleUnaryOperator IN_EXPO = x -> x <= 0.0 ? 0.0 : Math.pow(2.0, 10.0 * x - 10.0); + private static final DoubleUnaryOperator OUT_EXPO = x -> x >= 1.0 ? 1.0 : 1.0 - Math.pow(2.0, -10.0 * x); + private static final DoubleUnaryOperator IN_OUT_EXPO = x -> { + if (x <= 0.0) { + return 0.0; + } else if (x >= 1.0) { + return 1.0; + } else { + return x < 0.5 ? Math.pow(2.0, 20.0 * x - 10.0) / 2.0 : (2.0 - Math.pow(2.0, -20.0 * x + 10.0)) / 2.0; + } + }; + private static final DoubleUnaryOperator IN_CIRC = x -> 1.0 - Math.sqrt(1.0 - x * x); + private static final DoubleUnaryOperator OUT_CIRC = x -> Math.sqrt(1.0 - (x - 1.0) * (x - 1.0)); + private static final DoubleUnaryOperator IN_OUT_CIRC = x -> x < 0.5 + ? (1.0 - Math.sqrt(1.0 - Math.pow(2.0 * x, 2.0))) / 2.0 + : (Math.sqrt(1.0 - Math.pow(-2.0 * x + 2.0, 2.0)) + 1.0) / 2.0; + private static final DoubleUnaryOperator IN_BACK = x -> 2.70158 * x * x * x - 1.70158 * x * x; + private static final DoubleUnaryOperator OUT_BACK = x -> 1.0 + 2.70158 * Math.pow(x - 1.0, 3.0) + 1.70158 * Math.pow(x - 1.0, 2.0); + private static final DoubleUnaryOperator IN_OUT_BACK = x -> x < 0.5 + ? Math.pow(2.0 * x, 2.0) * (7.189819 * x - 2.5949095) / 2.0 + : (Math.pow(2.0 * x - 2.0, 2.0) * (3.5949095 * (2.0 * x - 2.0) + 2.5949095) + 2.0) / 2.0; + private static final DoubleUnaryOperator IN_ELASTIC = x -> { + if (x <= 0.0) { + return 0.0; + } else { + return x >= 1.0 ? 1.0 : -Math.pow(2.0, 10.0 * x - 10.0) * Math.sin((x * 10.0 - 10.75) * (Math.PI * 2.0 / 3.0)); + } + }; + private static final DoubleUnaryOperator OUT_ELASTIC = x -> { + if (x <= 0.0) { + return 0.0; + } else { + return x >= 1.0 ? 1.0 : Math.pow(2.0, -10.0 * x) * Math.sin((x * 10.0 - 0.75) * (Math.PI * 2.0 / 3.0)) + 1.0; + } + }; + private static final DoubleUnaryOperator IN_OUT_ELASTIC = x -> { + if (x <= 0.0) { + return 0.0; + } else if (x >= 1.0) { + return 1.0; + } else { + return x < 0.5 + ? -(Math.pow(2.0, 20.0 * x - 10.0) * Math.sin((20.0 * x - 11.125) * (Math.PI * 4.0 / 9.0))) / 2.0 + : Math.pow(2.0, -20.0 * x + 10.0) * Math.sin((20.0 * x - 11.125) * (Math.PI * 4.0 / 9.0)) / 2.0 + 1.0; + } + }; + private static final DoubleUnaryOperator OUT_BOUNCE = Easing.Fn::outBounce; + private static final DoubleUnaryOperator IN_BOUNCE = x -> 1.0 - outBounce(1.0 - x); + private static final DoubleUnaryOperator IN_OUT_BOUNCE = x -> x < 0.5 ? (1.0 - outBounce(1.0 - 2.0 * x)) / 2.0 : (1.0 + outBounce(2.0 * x - 1.0)) / 2.0; + + private static double outBounce(double x) { + if (x < 0.36363636363636365) { + return 7.5625 * x * x; + } else if (x < 0.7272727272727273) { + x -= 0.5454545454545454; + return 7.5625 * x * x + 0.75; + } else if (x < 0.9090909090909091) { + x -= 0.8181818181818182; + return 7.5625 * x * x + 0.9375; + } else { + x -= 0.9545454545454546; + return 7.5625 * x * x + 0.984375; + } + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/math/OrientedBoundingBox.java b/api/src/main/java/com/ticxo/modelengine/api/utils/math/OrientedBoundingBox.java new file mode 100644 index 0000000..2cc484b --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/math/OrientedBoundingBox.java @@ -0,0 +1,243 @@ +package com.ticxo.modelengine.api.utils.math; + +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.World; +import org.bukkit.Particle.DustOptions; +import org.bukkit.entity.ItemDisplay; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Consumer; +import org.bukkit.util.RayTraceResult; +import org.bukkit.util.Transformation; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OrientedBoundingBox { + private static final Vector3f GLOBAL_RIGHT = new Vector3f(1.0F, 0.0F, 0.0F); + private static final Vector3f GLOBAL_UP = new Vector3f(0.0F, 1.0F, 0.0F); + private static final Vector3f GLOBAL_FORWARD = new Vector3f(0.0F, 0.0F, 1.0F); + private final Vector3f origin; + private final Quaternionf rotation; + private final Vector3f right; + private final Vector3f up; + private final Vector3f forward; + private final float halfX; + private final float halfY; + private final float halfZ; + + public OrientedBoundingBox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { + this.origin = new Vector3f((maxX + minX) * 0.5F, (maxY + minY) * 0.5F, (maxZ + minZ) * 0.5F); + this.rotation = new Quaternionf(); + this.right = new Vector3f(GLOBAL_RIGHT); + this.up = new Vector3f(GLOBAL_UP); + this.forward = new Vector3f(GLOBAL_FORWARD); + this.halfX = (maxX - minX) * 0.5F; + this.halfY = (maxY - minY) * 0.5F; + this.halfZ = (maxZ - minZ) * 0.5F; + } + + public OrientedBoundingBox(Vector3f origin, Vector3f dimension, Vector3f rotation, float yaw) { + this(origin, dimension, new Quaternionf().rotationXYZ(rotation.x, rotation.y, rotation.z), yaw); + } + + public OrientedBoundingBox(Vector3f origin, Vector3f dimension, Quaternionf rotation, float yaw) { + this.origin = new Vector3f(origin); + this.rotation = rotation.rotateLocalY(yaw * (float) (Math.PI / 180.0), new Quaternionf()); + this.right = GLOBAL_RIGHT.rotate(this.rotation, new Vector3f()); + this.up = GLOBAL_UP.rotate(this.rotation, new Vector3f()); + this.forward = GLOBAL_FORWARD.rotate(this.rotation, new Vector3f()); + this.halfX = dimension.x * 0.5F; + this.halfY = dimension.y * 0.5F; + this.halfZ = dimension.z * 0.5F; + } + + public boolean intersects(BoundingBox aabb) { + return this.intersects( + new OrientedBoundingBox( + (float)aabb.getMinX(), (float)aabb.getMinY(), (float)aabb.getMinZ(), (float)aabb.getMaxX(), (float)aabb.getMaxY(), (float)aabb.getMaxZ() + ) + ); + } + + public boolean intersects(OrientedBoundingBox obb) { + Vector3f traversed = new Vector3f(obb.origin.x - this.origin.x, obb.origin.y - this.origin.y, obb.origin.z - this.origin.z); + Vector3f scaledRight = new Vector3f(this.right).mul(this.halfX); + Vector3f scaledUp = new Vector3f(this.up).mul(this.halfY); + Vector3f scaledForward = new Vector3f(this.forward).mul(this.halfZ); + Vector3f otherScaledRight = new Vector3f(obb.right).mul(obb.halfX); + Vector3f otherScaledUp = new Vector3f(obb.up).mul(obb.halfY); + Vector3f otherScaledForward = new Vector3f(obb.forward).mul(obb.halfZ); + + for (int i = 0; i < 15; i++) { + Vector3f check = this.getL(i, obb); + double t = this.projectionOnAxis(traversed, check); + double proj = this.projectionOnAxis(scaledRight, check) + + this.projectionOnAxis(scaledUp, check) + + this.projectionOnAxis(scaledForward, check) + + this.projectionOnAxis(otherScaledRight, check) + + this.projectionOnAxis(otherScaledUp, check) + + this.projectionOnAxis(otherScaledForward, check); + if (t > proj) { + return false; + } + } + + return true; + } + + public RayTraceResult rayTrace(@NotNull Vector3f start, @NotNull Vector3f direction, double maxDistance, Consumer consumer) { + if (!this.origin.isFinite()) { + return new RayTraceResult(new Vector(start.x + direction.x * maxDistance, start.y + direction.y * maxDistance, start.z + direction.z * maxDistance)); + } else { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vector3f relativeStart = start.sub(this.origin, new Vector3f()).rotate(inverse).add(this.origin); + Vector3f relativeDirection = new Vector3f(direction).rotate(inverse); + BoundingBox bb = BoundingBox.of(new Vector(this.origin.x, this.origin.y, this.origin.z), this.halfX, this.halfY, this.halfZ); + if (consumer != null) { + consumer.accept(bb); + } + + RayTraceResult result = bb.rayTrace( + new Vector(relativeStart.x, relativeStart.y, relativeStart.z), + new Vector(relativeDirection.x, relativeDirection.y, relativeDirection.z), + maxDistance + ); + if (result == null) { + return null; + } else { + Vector3f hitPosition = result.getHitPosition().toVector3f().sub(this.origin).rotate(this.rotation).add(this.origin); + return new RayTraceResult(new Vector(hitPosition.x, hitPosition.y, hitPosition.z), result.getHitBlockFace()); + } + } + } + + public boolean isWithinRange(@NotNull Vector3f point, double range) { + if (this.origin.isFinite() && Float.isFinite(this.halfX) && Float.isFinite(this.halfY) && Float.isFinite(this.halfZ)) { + double dx = this.origin.x - point.x; + double dy = this.origin.y - point.y; + double dz = this.origin.z - point.z; + float scale = Math.max(Math.max(Math.abs(this.origin.x), Math.abs(this.origin.y)), Math.abs(this.origin.z)); + double base = range + Math.sqrt((double)this.halfX * this.halfX + (double)this.halfY * this.halfY + (double)this.halfZ * this.halfZ); + double margin = 4.0 * Math.max(Math.ulp(scale + 1.0F), Math.ulp((float)base + 1.0F)); + double reach = base + margin; + return dx * dx + dy * dy + dz * dz <= reach * reach; + } else { + return true; + } + } + + public double distanceSquared(@NotNull Vector3f vector) { + if (!this.origin.isFinite()) { + return Double.NaN; + } else { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vector3f relativeVector = vector.sub(this.origin, new Vector3f()).rotate(inverse).add(this.origin); + BoundingBox bb = BoundingBox.of(new Vector(this.origin.x, this.origin.y, this.origin.z), this.halfX, this.halfY, this.halfZ); + return TMath.distanceSquaredToBoundingBox(Vector.fromJOML(relativeVector), bb); + } + } + + public boolean contains(@NotNull Vector3f vector) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vector3f relativeVector = vector.sub(this.origin, new Vector3f()).rotate(inverse).add(this.origin); + BoundingBox bb = BoundingBox.of(new Vector(this.origin.x, this.origin.y, this.origin.z), this.halfX, this.halfY, this.halfZ); + return bb.contains(Vector.fromJOML(relativeVector)); + } + + private double projectionOnAxis(Vector3f vector, Vector3f axis) { + return Math.abs(vector.dot(axis)); + } + + private Vector3f getL(int i, OrientedBoundingBox other) { + return switch (i) { + case 0 -> this.right; + case 1 -> this.up; + case 2 -> this.forward; + case 3 -> other.right; + case 4 -> other.up; + case 5 -> other.forward; + case 6 -> this.right.cross(other.right, new Vector3f()); + case 7 -> this.right.cross(other.up, new Vector3f()); + case 8 -> this.right.cross(other.forward, new Vector3f()); + case 9 -> this.up.cross(other.right, new Vector3f()); + case 10 -> this.up.cross(other.up, new Vector3f()); + case 11 -> this.up.cross(other.forward, new Vector3f()); + case 12 -> this.forward.cross(other.right, new Vector3f()); + case 13 -> this.forward.cross(other.up, new Vector3f()); + case 14 -> this.forward.cross(other.forward, new Vector3f()); + default -> throw new IllegalStateException("Unexpected value: " + i); + }; + } + + public ItemDisplay visualize(World world, ItemStack stack) { + Location location = new Location(world, this.origin.x, this.origin.y, this.origin.z); + return (ItemDisplay)world.spawn( + location, + ItemDisplay.class, + itemDisplay -> { + itemDisplay.setItemStack(stack); + itemDisplay.setTransformation( + new Transformation(new Vector3f(), this.rotation, new Vector3f(2.0F * this.halfX, 2.0F * this.halfY, 2.0F * this.halfZ), new Quaternionf()) + ); + } + ); + } + + public void visualize(World world) { + Vector3f offsetX = new Vector3f(this.right).mul(this.halfX); + Vector3f offsetY = new Vector3f(this.up).mul(this.halfY); + Vector3f offsetZ = new Vector3f(this.forward).mul(this.halfZ); + Vector3f offsetXN = new Vector3f(offsetX).mul(-1.0F); + Vector3f offsetYN = new Vector3f(offsetY).mul(-1.0F); + Vector3f offsetZN = new Vector3f(offsetZ).mul(-1.0F); + this.drawLine(offsetX, offsetY, offsetZ, world, Color.ORANGE, this.halfZ * 2.0F); + this.drawLine(offsetX, offsetYN, offsetZ, world, Color.ORANGE, this.halfZ * 2.0F); + this.drawLine(offsetXN, offsetY, offsetZ, world, Color.ORANGE, this.halfZ * 2.0F); + this.drawLine(offsetXN, offsetYN, offsetZ, world, Color.ORANGE, this.halfZ * 2.0F); + this.drawLine(offsetY, offsetZ, offsetX, world, Color.GREEN, this.halfX * 2.0F); + this.drawLine(offsetY, offsetZN, offsetX, world, Color.GREEN, this.halfX * 2.0F); + this.drawLine(offsetYN, offsetZ, offsetX, world, Color.GREEN, this.halfX * 2.0F); + this.drawLine(offsetYN, offsetZN, offsetX, world, Color.GREEN, this.halfX * 2.0F); + this.drawLine(offsetZ, offsetX, offsetY, world, Color.AQUA, this.halfY * 2.0F); + this.drawLine(offsetZ, offsetXN, offsetY, world, Color.AQUA, this.halfY * 2.0F); + this.drawLine(offsetZN, offsetX, offsetY, world, Color.AQUA, this.halfY * 2.0F); + this.drawLine(offsetZN, offsetXN, offsetY, world, Color.AQUA, this.halfY * 2.0F); + } + + private void drawLine(Vector3f offset1, Vector3f offset2, Vector3f line, World world, Color color, double dist) { + Vector3f offset = new Vector3f(offset1).add(offset2); + Vector3f pointA = new Vector3f(offset).add(line); + Vector3f pointB = new Vector3f(offset).sub(line); + double ratio = 1.0 / dist; + + for (double i = 0.0; i < dist; i += 0.1) { + Vector3f point = TMath.lerp(pointA, pointB, i * ratio); + world.spawnParticle(Particle.REDSTONE, this.origin.x + point.x, this.origin.y + point.y, this.origin.z + point.z, 1, new DustOptions(color, 0.2F)); + } + } + + @Override + public String toString() { + return "OrientedBoundingBox(origin=" + + this.origin + + ", rotation=" + + this.rotation + + ", right=" + + this.right + + ", up=" + + this.up + + ", forward=" + + this.forward + + ", halfX=" + + this.halfX + + ", halfY=" + + this.halfY + + ", halfZ=" + + this.halfZ + + ")"; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/math/SafeTransform.java b/api/src/main/java/com/ticxo/modelengine/api/utils/math/SafeTransform.java new file mode 100644 index 0000000..18f7e06 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/math/SafeTransform.java @@ -0,0 +1,90 @@ +package com.ticxo.modelengine.api.utils.math; + +import java.lang.invoke.VarHandle; +import java.util.function.Consumer; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class SafeTransform extends Transform { + private final Transform lastTransform = new Transform(); + private final Transform safe = new Transform(); + + public void recordLast() { + this.lastTransform.position.set(this.position); + this.lastTransform.leftEuler.set(this.leftEuler); + this.lastTransform.scale.set(this.scale); + this.lastTransform.rightEuler.set(this.rightEuler); + this.lastTransform.leftQuaternion.set(this.leftQuaternion); + this.lastTransform.rightQuaternion.set(this.rightQuaternion); + } + + public void recordSafe() { + this.safe.position.set(this.position); + this.safe.leftEuler.set(this.leftEuler); + this.safe.scale.set(this.scale); + this.safe.rightEuler.set(this.rightEuler); + this.safe.leftQuaternion.set(this.leftQuaternion); + this.safe.rightQuaternion.set(this.rightQuaternion); + VarHandle.releaseFence(); + } + + public Vector3f getSafePosition() { + VarHandle.acquireFence(); + return this.safe.getPosition(); + } + + public Vector3f getSafeLeftEuler() { + VarHandle.acquireFence(); + return this.safe.getLeftEuler(); + } + + public Vector3f getSafeScale() { + VarHandle.acquireFence(); + return this.safe.getScale(); + } + + public Vector3f getSafeRightEuler() { + VarHandle.acquireFence(); + return this.safe.getRightEuler(); + } + + public Quaternionf getSafeLeftQuaternion() { + VarHandle.acquireFence(); + return this.safe.getLeftQuaternion(); + } + + public Quaternionf getSafeRightQuaternion() { + VarHandle.acquireFence(); + return this.safe.getRightQuaternion(); + } + + public void mutateSafe(Consumer consumer) { + VarHandle.acquireFence(); + consumer.accept(this.safe); + VarHandle.releaseFence(); + } + + public Vector3f getLastPosition() { + return this.lastTransform.getPosition(); + } + + public Vector3f getLastLeftEuler() { + return this.lastTransform.getLeftEuler(); + } + + public Vector3f getLastScale() { + return this.lastTransform.getScale(); + } + + public Vector3f getLastRightEuler() { + return this.lastTransform.getRightEuler(); + } + + public Quaternionf getLastLeftQuaternion() { + return this.lastTransform.getLeftQuaternion(); + } + + public Quaternionf getLastRightQuaternion() { + return this.lastTransform.getRightQuaternion(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/math/TMath.java b/api/src/main/java/com/ticxo/modelengine/api/utils/math/TMath.java new file mode 100644 index 0000000..e62fd1a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/math/TMath.java @@ -0,0 +1,773 @@ +package com.ticxo.modelengine.api.utils.math; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.UUID; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.EulerAngle; +import org.bukkit.util.Transformation; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.joml.Matrix3d; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaterniond; +import org.joml.Quaternionf; +import org.joml.Vector3d; +import org.joml.Vector3f; +import org.joml.Vector4f; + +public class TMath { + public static final float PI = (float) Math.PI; + public static final double TAU = Math.PI * 2; + public static final double PI_2 = Math.PI / 2; + public static final double PI_4 = Math.PI / 4; + public static final float EPSILON = 1.0E-5F; + public static final float JOML_EPSILON = 0.001F; + public static final double D_EPSILON = 1.0E-5; + public static final float DEG2RAD = (float) (Math.PI / 180.0); + public static final float RAD2DEG = (float) (180.0 / Math.PI); + public static final double D_DEG2RAD = Math.PI / 180.0; + public static final double D_RAD2DEG = 180.0 / Math.PI; + protected static float LOWER_SCALE_LIMIT = 0.0F; + protected static double MOVEMENT_RESOLUTION = 0.001; + + public static boolean isSimilar(float a, float b) { + return org.joml.Math.abs(b - a) < 1.0E-5F; + } + + public static boolean isSimilar(double a, double b) { + return org.joml.Math.abs(b - a) < 1.0E-5F; + } + + public static boolean isSimilar(float a, float b, float epsilon) { + return org.joml.Math.abs(b - a) < epsilon; + } + + public static boolean isSimilar(Vector3f a, Vector3f b) { + if (a == null && b == null) { + return true; + } else { + return a != null && b != null ? isSimilar(a.x, b.x, 0.001F) && isSimilar(a.y, b.y, 0.001F) && isSimilar(a.z, b.z, 0.001F) : false; + } + } + + public static boolean isSimilar(Quaternionf a, Quaternionf b) { + if (a == null && b == null) { + return true; + } else { + return a != null && b != null + ? isSimilar(a.x, b.x, 0.001F) && isSimilar(a.y, b.y, 0.001F) && isSimilar(a.z, b.z, 0.001F) && isSimilar(a.w, b.w, 0.001F) + : false; + } + } + + public static double clamp(double value, double min, double max) { + return org.joml.Math.min(org.joml.Math.max(value, min), max); + } + + public static float clamp(float value, float min, float max) { + return org.joml.Math.min(org.joml.Math.max(value, min), max); + } + + public static int clamp(int value, int min, int max) { + return org.joml.Math.min(org.joml.Math.max(value, min), max); + } + + public static int absMax(float a, float b, float c) { + float absA = org.joml.Math.abs(a); + float absB = org.joml.Math.abs(b); + float absC = org.joml.Math.abs(c); + if (absA > absB) { + return absA > absC ? 0 : 2; + } else { + return absB > absC ? 1 : 2; + } + } + + public static byte setBit(byte dataItem, int bitOffset, boolean flag) { + byte f = (byte)(1 << bitOffset); + return (byte)(flag ? dataItem | f : dataItem & ~f); + } + + public static boolean getBit(byte dataItem, int bitOffset) { + return (dataItem & 1 << bitOffset) != 0; + } + + public static int floor(double val) { + return (int)org.joml.Math.floor(val); + } + + public static int ceil(double val) { + return (int)org.joml.Math.ceil(val); + } + + public static int tryParse(String val, int def) { + if (val == null) { + return def; + } else { + try { + return Integer.parseInt(val); + } catch (NumberFormatException var3) { + return def; + } + } + } + + public static double tryParse(String val, double def) { + if (val == null) { + return def; + } else { + try { + return Double.parseDouble(val); + } catch (NumberFormatException var4) { + return def; + } + } + } + + public static boolean isBoundingBoxWithinDistance(@NotNull Vector start, @NotNull Vector direction, BoundingBox boundingBox, double maxDistance) { + double startX = start.getX(); + double startY = start.getY(); + double startZ = start.getZ(); + Vector dir = direction.clone(); + if (dir.getX() == 0.0) { + dir.setX(0); + } + + if (dir.getY() == 0.0) { + dir.setY(0); + } + + if (dir.getZ() == 0.0) { + dir.setZ(0); + } + + dir.normalize(); + double dirX = dir.getX(); + double dirY = dir.getY(); + double dirZ = dir.getZ(); + double divX = 1.0 / dirX; + double divY = 1.0 / dirY; + double divZ = 1.0 / dirZ; + double tMin; + double tMax; + if (dirX >= 0.0) { + tMin = (boundingBox.getMinX() - startX) * divX; + tMax = (boundingBox.getMaxX() - startX) * divX; + } else { + tMin = (boundingBox.getMaxX() - startX) * divX; + tMax = (boundingBox.getMinX() - startX) * divX; + } + + double tyMin; + double tyMax; + if (dirY >= 0.0) { + tyMin = (boundingBox.getMinY() - startY) * divY; + tyMax = (boundingBox.getMaxY() - startY) * divY; + } else { + tyMin = (boundingBox.getMaxY() - startY) * divY; + tyMax = (boundingBox.getMinY() - startY) * divY; + } + + if (!(tMin > tyMax) && !(tMax < tyMin)) { + if (tyMin > tMin) { + tMin = tyMin; + } + + if (tyMax < tMax) { + tMax = tyMax; + } + + double tzMin; + double tzMax; + if (dirZ >= 0.0) { + tzMin = (boundingBox.getMinZ() - startZ) * divZ; + tzMax = (boundingBox.getMaxZ() - startZ) * divZ; + } else { + tzMin = (boundingBox.getMaxZ() - startZ) * divZ; + tzMax = (boundingBox.getMinZ() - startZ) * divZ; + } + + if (!(tMin > tzMax) && !(tMax < tzMin)) { + if (tzMin > tMin) { + tMin = tzMin; + } + + if (tzMax < tMax) { + tMax = tzMax; + } + + return tMax < 0.0 ? false : !(tMin > maxDistance); + } else { + return false; + } + } else { + return false; + } + } + + public static double distanceSquaredToBoundingBox(Vector origin, BoundingBox box) { + double x = org.joml.Math.max(org.joml.Math.abs(origin.getX() - box.getCenterX()) - box.getWidthX() * 0.5, 0.0); + double y = org.joml.Math.max(org.joml.Math.abs(origin.getY() - box.getCenterY()) - box.getHeight() * 0.5, 0.0); + double z = org.joml.Math.max(org.joml.Math.abs(origin.getZ() - box.getCenterZ()) - box.getWidthZ() * 0.5, 0.0); + return x * x + y * y + z * z; + } + + public static boolean isSimilar(Vector a, Vector b) { + return org.joml.Math.abs(b.getX() - a.getX()) < MOVEMENT_RESOLUTION + && org.joml.Math.abs(b.getY() - a.getY()) < MOVEMENT_RESOLUTION + && org.joml.Math.abs(b.getZ() - a.getZ()) < MOVEMENT_RESOLUTION; + } + + public static EulerAngle makeAngle(double x, double y, double z) { + return new EulerAngle(org.joml.Math.toRadians(x), org.joml.Math.toRadians(y), org.joml.Math.toRadians(z)); + } + + public static EulerAngle add(EulerAngle a, EulerAngle b) { + return a.add(b.getX(), b.getY(), b.getZ()); + } + + public static float wrapRadian(float r) { + r = (float)(r % (Math.PI * 2)); + if (r < -Math.PI) { + r = (float)(r + (Math.PI * 2)); + } + + if (r > Math.PI) { + r = (float)(r - (Math.PI * 2)); + } + + return r; + } + + public static float wrapDegree(float r) { + if (r >= -180.0F && r <= 180.0F) { + return r; + } else { + r %= 360.0F; + if (r < -180.0F) { + r += 360.0F; + } + + if (r > 180.0F) { + r -= 360.0F; + } + + return r; + } + } + + public static float radianDifference(float a, float b) { + return wrapRadian(b - a); + } + + public static float degreeDifference(float a, float b) { + return wrapDegree(b - a); + } + + public static float rotateIfNecessary(float current, float target, float negativeClamp, float positiveClamp) { + float delta = degreeDifference(current, target); + float clampedDelta = clamp(delta, negativeClamp, positiveClamp); + return target - clampedDelta; + } + + public static byte rotToByte(float rot) { + return (byte)(rot * 256.0F / 360.0F); + } + + public static float byteToRot(byte rot) { + return rot / 256.0F * 360.0F; + } + + public static double lerp(double a, double b, double t) { + return (1.0 - t) * a + t * b; + } + + public static double invLerp(double a, double b, double l) { + return (l - a) / (b - a); + } + + public static float lerp(float a, float b, float t) { + return (1.0F - t) * a + t * b; + } + + public static float invLerp(float a, float b, float l) { + return (l - a) / (b - a); + } + + public static double lerp(double a, double b, double aT, double bT) { + return aT * a + bT * b; + } + + public static float lerp(float a, float b, float aT, float bT) { + return aT * a + bT * b; + } + + public static double rotLerp(double a, double b, double t) { + return a + degreeDifference((float)a, (float)b) * t; + } + + public static float rotLerp(float a, float b, double t) { + return (float)(a + degreeDifference(a, b) * t); + } + + public static double smoothLerp(double a, double b, double c, double d, double t) { + double t0 = 0.0; + double t1 = 1.0; + double t2 = 2.0; + double t3 = 3.0; + t = (t2 - t1) * t + t1; + double a1 = lerp(a, b, (t1 - t) / (t1 - t0), (t - t0) / (t1 - t0)); + double a2 = lerp(b, c, (t2 - t) / (t2 - t1), (t - t1) / (t2 - t1)); + double a3 = lerp(c, d, (t3 - t) / (t3 - t2), (t - t2) / (t3 - t2)); + double b1 = lerp(a1, a2, (t2 - t) / (t2 - t0), (t - t0) / (t2 - t0)); + double b2 = lerp(a2, a3, (t3 - t) / (t3 - t1), (t - t1) / (t3 - t1)); + return lerp(b1, b2, (t2 - t) / (t2 - t1), (t - t1) / (t2 - t1)); + } + + public static Vector lerp(Vector a, Vector b, double t) { + return new Vector(lerp(a.getX(), b.getX(), t), lerp(a.getY(), b.getY(), t), lerp(a.getZ(), b.getZ(), t)); + } + + public static Vector lerp(Vector a, Vector b, double aT, double bT) { + return new Vector(lerp(a.getX(), b.getX(), aT, bT), lerp(a.getY(), b.getY(), aT, bT), lerp(a.getZ(), b.getZ(), aT, bT)); + } + + public static Vector3f lerp(Vector3f a, Vector3f b, double t) { + return new Vector3f((float)lerp((double)a.x, (double)b.x, t), (float)lerp((double)a.y, (double)b.y, t), (float)lerp((double)a.z, (double)b.z, t)); + } + + public static Vector3f lerp(Vector3f a, Vector3f b, float aT, float bT) { + return new Vector3f(lerp(a.x, b.x, aT, bT), lerp(a.y, b.y, aT, bT), lerp(a.z, b.z, aT, bT)); + } + + public static Vector smoothLerp(Vector a, Vector b, Vector c, Vector d, double t) { + double t0 = 0.0; + double t1 = 1.0; + double t2 = 2.0; + double t3 = 3.0; + t = (t2 - t1) * t + t1; + Vector a1 = lerp(a, b, (t1 - t) / (t1 - t0), (t - t0) / (t1 - t0)); + Vector a2 = lerp(b, c, (t2 - t) / (t2 - t1), (t - t1) / (t2 - t1)); + Vector a3 = lerp(c, d, (t3 - t) / (t3 - t2), (t - t2) / (t3 - t2)); + Vector b1 = lerp(a1, a2, (t2 - t) / (t2 - t0), (t - t0) / (t2 - t0)); + Vector b2 = lerp(a2, a3, (t3 - t) / (t3 - t1), (t - t1) / (t3 - t1)); + return lerp(b1, b2, (t2 - t) / (t2 - t1), (t - t1) / (t2 - t1)); + } + + public static Vector3f smoothLerp(Vector3f a, Vector3f b, Vector3f c, Vector3f d, float t) { + float t0 = 0.0F; + float t1 = 1.0F; + float t2 = 2.0F; + float t3 = 3.0F; + t = (t2 - t1) * t + t1; + Vector3f a1 = lerp(a, b, (t1 - t) / (t1 - t0), (t - t0) / (t1 - t0)); + Vector3f a2 = lerp(b, c, (t2 - t) / (t2 - t1), (t - t1) / (t2 - t1)); + Vector3f a3 = lerp(c, d, (t3 - t) / (t3 - t2), (t - t2) / (t3 - t2)); + Vector3f b1 = lerp(a1, a2, (t2 - t) / (t2 - t0), (t - t0) / (t2 - t0)); + Vector3f b2 = lerp(a2, a3, (t3 - t) / (t3 - t1), (t - t1) / (t3 - t1)); + return lerp(b1, b2, (t2 - t) / (t2 - t1), (t - t1) / (t2 - t1)); + } + + public static float cubicBezierTime(float u1, float u2, float s) { + float inv = 1.0F - s; + return 3.0F * u1 * s * inv * inv + 3.0F * u2 * s * s * inv + s * s * s; + } + + public static float cubicBezierTimeDerivative(float u1, float u2, float s) { + float inv = 1.0F - s; + return 3.0F * u1 * inv * (1.0F - 3.0F * s) + 3.0F * u2 * s * (2.0F - 3.0F * s) + 3.0F * s * s; + } + + public static float cubicBezierSolve(float u1, float u2, float t) { + if (t <= 0.0F) { + return 0.0F; + } else if (t >= 1.0F) { + return 1.0F; + } else { + float s = t; + + for (int i = 0; i < 8; i++) { + float error = cubicBezierTime(u1, u2, s) - t; + if (error < 0.0F) { + error = -error; + } + + if (error < 1.0E-5F) { + return s; + } + + float slope = cubicBezierTimeDerivative(u1, u2, s); + if (slope < 1.0E-6F) { + break; + } + + s = clamp(s - error / slope, 0.0F, 1.0F); + } + + float lo = 0.0F; + float hi = 1.0F; + s = t; + + for (int i = 0; i < 20; i++) { + if (cubicBezierTime(u1, u2, s) < t) { + lo = s; + } else { + hi = s; + } + + s = (lo + hi) * 0.5F; + } + + return s; + } + } + + public static float cubicBezierValue(float v0, float v1, float v2, float v3, float s) { + float inv = 1.0F - s; + float invSq = inv * inv; + float sq = s * s; + return invSq * inv * v0 + 3.0F * invSq * s * v1 + 3.0F * inv * sq * v2 + sq * s * v3; + } + + public static EulerAngle lerp(EulerAngle a, EulerAngle b, double t) { + return new EulerAngle(lerp(a.getX(), b.getX(), t), lerp(a.getY(), b.getY(), t), lerp(a.getZ(), b.getZ(), t)); + } + + public static EulerAngle lerp(EulerAngle a, EulerAngle b, double aT, double bT) { + return new EulerAngle(lerp(a.getX(), b.getX(), aT, bT), lerp(a.getY(), b.getY(), aT, bT), lerp(a.getZ(), b.getZ(), aT, bT)); + } + + public static EulerAngle smoothLerp(EulerAngle a, EulerAngle b, EulerAngle c, EulerAngle d, double t) { + double t0 = 0.0; + double t1 = 1.0; + double t2 = 2.0; + double t3 = 3.0; + t = (t2 - t1) * t + t1; + EulerAngle a1 = lerp(a, b, (t1 - t) / (t1 - t0), (t - t0) / (t1 - t0)); + EulerAngle a2 = lerp(b, c, (t2 - t) / (t2 - t1), (t - t1) / (t2 - t1)); + EulerAngle a3 = lerp(c, d, (t3 - t) / (t3 - t2), (t - t2) / (t3 - t2)); + EulerAngle b1 = lerp(a1, a2, (t2 - t) / (t2 - t0), (t - t0) / (t2 - t0)); + EulerAngle b2 = lerp(a2, a3, (t3 - t) / (t3 - t1), (t - t1) / (t3 - t1)); + return lerp(b1, b2, (t2 - t) / (t2 - t1), (t - t1) / (t2 - t1)); + } + + public static Vector3f slerp(Vector3f a, Vector3f b, double t) { + if (a.equals(b)) { + return a; + } else { + Quaternionf qA = new Quaternionf().rotationZYX(a.z, a.y, a.x); + Quaternionf qB = new Quaternionf().rotationZYX(b.z, b.y, b.x); + qA.slerp(qB, (float)t); + return getEulerAnglesZYX(qA, new Vector3f()); + } + } + + public static Vector3f getEulerAnglesZYX(Quaternionf quat, Vector3f eulerAngles) { + return matToEulerZYX(quat.get(new Matrix3f()), eulerAngles); + } + + public static Vector3f matToEulerZYX(Matrix3f mat, Vector3f result) { + result.y = org.joml.Math.asin(-org.joml.Math.clamp(mat.m02, -1.0F, 1.0F)); + if (org.joml.Math.abs(mat.m02) < 0.9999999) { + result.x = org.joml.Math.atan2(mat.m12, mat.m22); + result.z = org.joml.Math.atan2(mat.m01, mat.m00); + } else { + result.x = 0.0F; + result.z = org.joml.Math.atan2(-mat.m10, mat.m11); + } + + return result; + } + + public static Vector3d getEulerAnglesZYX(Quaterniond quat, Vector3d eulerAngles) { + return matToEulerZYX(quat.get(new Matrix3d()), eulerAngles); + } + + public static Vector3d matToEulerZYX(Matrix3d mat, Vector3d result) { + result.y = org.joml.Math.asin(-clamp(mat.m02, -1.0, 1.0)); + if (org.joml.Math.abs(mat.m02) < 0.9999999) { + result.x = org.joml.Math.atan2(mat.m12, mat.m22); + result.z = org.joml.Math.atan2(mat.m01, mat.m00); + } else { + result.x = 0.0; + result.z = org.joml.Math.atan2(-mat.m10, mat.m11); + } + + return result; + } + + public static Vector3f toEulerZYX(Quaternionf quaternion, Vector3f dest) { + return getEulerAnglesZYX(quaternion, dest).mul((float) (180.0 / Math.PI)); + } + + public static Vector3d toEulerZYX(Quaterniond quaternion) { + return getEulerAnglesZYX(quaternion, new Vector3d()).mul(180.0 / Math.PI); + } + + public static Vector3d toEulerXYZ(Quaterniond quaternion) { + return matToEulerXYZ(quaternion.get(new Matrix3d()), new Vector3d()).mul(180.0 / Math.PI); + } + + public static Vector3d matToEulerXYZ(Matrix3d mat, Vector3d result) { + result.y = org.joml.Math.asin(clamp(mat.m20, -1.0, 1.0)); + if (org.joml.Math.abs(mat.m20) < 0.9999999) { + result.x = org.joml.Math.atan2(-mat.m21, mat.m22); + result.z = org.joml.Math.atan2(-mat.m10, mat.m00); + } else { + result.x = org.joml.Math.atan2(mat.m12, mat.m11); + result.z = 0.0; + } + + return result; + } + + public static Quaterniond fromEulerZYX(Vector3d euler) { + return new Quaterniond().rotateZYX(euler.z * (Math.PI / 180.0), euler.y * (Math.PI / 180.0), euler.x * (Math.PI / 180.0)); + } + + public static Quaterniond fromEulerXYZ(Vector3d euler) { + return new Quaterniond().rotateXYZ(euler.x * (Math.PI / 180.0), euler.y * (Math.PI / 180.0), euler.z * (Math.PI / 180.0)); + } + + public static boolean isInterval(double value, double interval) { + double half = interval * 0.5; + return isSimilar(org.joml.Math.abs(org.joml.Math.abs(value) % interval - half), half); + } + + public static boolean isAlmostBetween(double val, double min, double max) { + return val >= min && val <= max ? true : isSimilar(val, min) || isSimilar(val, max); + } + + public static Vector3f toPitchYaw(Vector3f dir) { + double hMagnitude = org.joml.Math.sqrt(dir.x * dir.x + dir.z * dir.z); + float pitch = (float)org.joml.Math.atan2(-dir.y, hMagnitude) * (float) (180.0 / Math.PI); + float yaw = org.joml.Math.atan2(-dir.x, dir.z) * (float) (180.0 / Math.PI); + return new Vector3f(pitch, yaw, 0.0F); + } + + public static Quaternionf toQuaternion(Vector3f euler) { + return new Quaternionf().rotateZYX(euler.z, euler.y, euler.x); + } + + public static Quaternionf toQuaternion(Vector3f euler, Quaternionf dest) { + return dest.identity().rotateZYX(euler.z, euler.y, euler.x); + } + + public static Vector3f fixVector(Vector3f v) { + if (isSimilar(v.x, 0.0F)) { + v.x = 0.0F; + } + + if (isSimilar(v.y, 0.0F)) { + v.y = 0.0F; + } + + if (isSimilar(v.z, 0.0F)) { + v.z = 0.0F; + } + + return v; + } + + public static Vector3d fixVector(Vector3d v) { + if (isSimilar(v.x, 0.0)) { + v.x = 0.0; + } + + if (isSimilar(v.y, 0.0)) { + v.y = 0.0; + } + + if (isSimilar(v.z, 0.0)) { + v.z = 0.0; + } + + return v; + } + + public static Vector3d fixEuler(Vector3d v) { + fixVector(v); + v.x = org.joml.Math.round(v.x * 10000.0) * 1.0E-4; + v.y = org.joml.Math.round(v.y * 10000.0) * 1.0E-4; + v.z = org.joml.Math.round(v.z * 10000.0) * 1.0E-4; + return v; + } + + public static Quaternionf fixQuaternion(Quaternionf q) { + if (isSimilar(q.x, 0.0F)) { + q.x = 0.0F; + } + + if (isSimilar(q.y, 0.0F)) { + q.y = 0.0F; + } + + if (isSimilar(q.z, 0.0F)) { + q.z = 0.0F; + } + + if (isSimilar(q.w, 0.0F)) { + q.w = 0.0F; + } + + return q; + } + + public static Quaterniond fixQuaternion(Quaterniond q) { + if (isSimilar(q.x, 0.0)) { + q.x = 0.0; + } + + if (isSimilar(q.y, 0.0)) { + q.y = 0.0; + } + + if (isSimilar(q.z, 0.0)) { + q.z = 0.0; + } + + if (isSimilar(q.w, 0.0)) { + q.w = 0.0; + } + + return q; + } + + public static Vector3f wrap(Float[] vec) { + return new Vector3f(vec[0], vec[1], vec[2]); + } + + public static float[] unwrap(Vector3f vec) { + return new float[]{vec.x, vec.y, vec.z}; + } + + public static float[] unwrap(Vector3d vec) { + return new float[]{(float)vec.x, (float)vec.y, (float)vec.z}; + } + + public static Transformation createIdentityTransform() { + return new Transformation(new Vector3f(), new Quaternionf(), new Vector3f(1.0F), new Quaternionf()); + } + + public static Vector3f transform(Matrix4f transform, Vector3f pos) { + Vector4f vec = transform.transform(new Vector4f(pos, 1.0F)); + return new Vector3f(vec.x, vec.y, vec.z); + } + + public static void clampedScale(Matrix4f mat, Vector3f scale) { + if (LOWER_SCALE_LIMIT == 0.0) { + mat.scale(scale); + } else { + float sx = clampedScale(scale.x); + float sy = clampedScale(scale.y); + float sz = clampedScale(scale.z); + float m00 = mat.m00() * sx; + float m10 = mat.m10() * sy; + float m20 = mat.m20() * sz; + if (!(Vector3f.lengthSquared(m00, m10, m20) > LOWER_SCALE_LIMIT * LOWER_SCALE_LIMIT)) { + m00 = clampedScale(m00); + m10 = clampedScale(m10); + m20 = clampedScale(m20); + } + + float m01 = mat.m01() * sx; + float m11 = mat.m11() * sy; + float m21 = mat.m21() * sz; + if (!(Vector3f.lengthSquared(m01, m11, m21) > LOWER_SCALE_LIMIT * LOWER_SCALE_LIMIT)) { + m01 = clampedScale(m01); + m11 = clampedScale(m11); + m21 = clampedScale(m21); + } + + float m02 = mat.m02() * sx; + float m12 = mat.m12() * sy; + float m22 = mat.m22() * sz; + if (!(Vector3f.lengthSquared(m02, m12, m22) > LOWER_SCALE_LIMIT * LOWER_SCALE_LIMIT)) { + m02 = clampedScale(m02); + m12 = clampedScale(m12); + m22 = clampedScale(m22); + } + + mat.set( + m00, + m01, + m02, + mat.m03() * scale.x, + m10, + m11, + m12, + mat.m13() * scale.y, + m20, + m21, + m22, + mat.m23() * scale.z, + mat.m30(), + mat.m31(), + mat.m32(), + mat.m33() + ); + } + } + + private static float clampedScale(float val) { + float sign = org.joml.Math.signum(val); + return sign == 0.0F ? LOWER_SCALE_LIMIT : sign * org.joml.Math.max(org.joml.Math.abs(val), LOWER_SCALE_LIMIT); + } + + public static Vector3f zerofyScale(Vector3f vec) { + return LOWER_SCALE_LIMIT == 0.0 + ? vec + : new Vector3f( + LOWER_SCALE_LIMIT >= org.joml.Math.abs(vec.x) ? 0.0F : vec.x, + LOWER_SCALE_LIMIT >= org.joml.Math.abs(vec.y) ? 0.0F : vec.y, + LOWER_SCALE_LIMIT >= org.joml.Math.abs(vec.z) ? 0.0F : vec.z + ); + } + + public static Vector3f zerofyScale(Vector3f vec, Vector3f dest) { + return LOWER_SCALE_LIMIT == 0.0 + ? dest.set(vec) + : dest.set( + LOWER_SCALE_LIMIT >= org.joml.Math.abs(vec.x) ? 0.0F : vec.x, + LOWER_SCALE_LIMIT >= org.joml.Math.abs(vec.y) ? 0.0F : vec.y, + LOWER_SCALE_LIMIT >= org.joml.Math.abs(vec.z) ? 0.0F : vec.z + ); + } + + public static String toString(EulerAngle angle) { + return String.format("[%s, %s, %s]", org.joml.Math.toDegrees(angle.getX()), org.joml.Math.toDegrees(angle.getY()), org.joml.Math.toDegrees(angle.getZ())); + } + + public static UUID parseUUID(String uuid) { + try { + return UUID.fromString(uuid); + } catch (IllegalArgumentException var6) { + if (uuid.length() != 32) { + throw var6; + } else { + long first = Long.parseUnsignedLong(uuid.substring(0, 16), 16); + long last = Long.parseUnsignedLong(uuid.substring(16), 16); + return new UUID(first, last); + } + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> LOWER_SCALE_LIMIT = (float)ConfigProperty.LOWER_SCALE_LIMIT.getDouble()); + } + + public static enum SlerpMode { + SLERP, + ONLERP; + + public static TMath.SlerpMode get(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException var2) { + return SLERP; + } + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/math/Transform.java b/api/src/main/java/com/ticxo/modelengine/api/utils/math/Transform.java new file mode 100644 index 0000000..841fb67 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/math/Transform.java @@ -0,0 +1,137 @@ +package com.ticxo.modelengine.api.utils.math; + +import java.util.function.Consumer; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class Transform { + protected final Vector3f position = new Vector3f(); + protected final Vector3f leftEuler = new Vector3f(); + protected final Vector3f scale = new Vector3f(1.0F); + protected final Vector3f rightEuler = new Vector3f(); + protected final Quaternionf leftQuaternion = new Quaternionf(); + protected final Quaternionf rightQuaternion = new Quaternionf(); + + public void identity() { + this.position.set(0.0F); + this.leftEuler.set(0.0F); + this.scale.set(1.0F); + this.rightEuler.set(0.0F); + this.leftQuaternion.identity(); + this.rightQuaternion.identity(); + } + + public void set(Transform other) { + this.position.set(other.position); + this.leftEuler.set(other.leftEuler); + this.scale.set(other.scale); + this.rightEuler.set(other.rightEuler); + this.leftQuaternion.set(other.leftQuaternion); + this.rightQuaternion.set(other.rightQuaternion); + } + + public Vector3f getPosition() { + return new Vector3f(this.position); + } + + public Vector3f getLeftEuler() { + return new Vector3f(this.leftEuler); + } + + public Vector3f getScale() { + return new Vector3f(this.scale); + } + + public Vector3f getRightEuler() { + return new Vector3f(this.rightEuler); + } + + public Quaternionf getLeftQuaternion() { + return new Quaternionf(this.leftQuaternion); + } + + public Quaternionf getRightQuaternion() { + return new Quaternionf(this.rightQuaternion); + } + + public Vector3f getPosition(Vector3f dest) { + return dest.set(this.position); + } + + public Vector3f getScale(Vector3f dest) { + return dest.set(this.scale); + } + + public Quaternionf getLeftQuaternion(Quaternionf dest) { + return dest.set(this.leftQuaternion); + } + + public Quaternionf getRightQuaternion(Quaternionf dest) { + return dest.set(this.rightQuaternion); + } + + public Vector3f setPosition(Vector3f value) { + return this.position.set(value); + } + + public Vector3f setLeftEuler(Vector3f value) { + this.leftEuler.set(value); + TMath.toQuaternion(this.leftEuler, this.leftQuaternion); + return this.leftEuler; + } + + public Vector3f setScale(Vector3f value) { + return this.scale.set(value); + } + + public Vector3f setRightEuler(Vector3f value) { + this.rightEuler.set(value); + TMath.toQuaternion(this.rightEuler, this.rightQuaternion); + return this.rightEuler; + } + + public Quaternionf setLeftQuaternion(Quaternionf value) { + this.leftQuaternion.set(value); + TMath.getEulerAnglesZYX(this.leftQuaternion, this.leftEuler); + return this.leftQuaternion; + } + + public Quaternionf setRightQuaternion(Quaternionf value) { + this.rightQuaternion.set(value); + TMath.getEulerAnglesZYX(this.rightQuaternion, this.rightEuler); + return this.rightQuaternion; + } + + public void mutatePosition(Consumer mutator) { + mutator.accept(this.position); + } + + public void mutateLeftEuler(Consumer mutator) { + mutator.accept(this.leftEuler); + TMath.toQuaternion(this.leftEuler, this.leftQuaternion); + } + + public void mutateScale(Consumer mutator) { + mutator.accept(this.scale); + } + + public void mutateRightEuler(Consumer mutator) { + mutator.accept(this.rightEuler); + TMath.toQuaternion(this.rightEuler, this.rightQuaternion); + } + + public void mutateLeftQuaternion(Consumer mutator) { + mutator.accept(this.leftQuaternion); + TMath.toEulerZYX(this.leftQuaternion, this.leftEuler); + } + + public void mutateRightQuaternion(Consumer mutator) { + mutator.accept(this.rightQuaternion); + TMath.toEulerZYX(this.rightQuaternion, this.rightEuler); + } + + public Matrix4f createMatrix() { + return new Matrix4f().translate(this.position).rotate(this.leftQuaternion).scale(this.scale).rotate(this.rightQuaternion); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/meta/IMetaHolder.java b/api/src/main/java/com/ticxo/modelengine/api/utils/meta/IMetaHolder.java new file mode 100644 index 0000000..cdc223c --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/meta/IMetaHolder.java @@ -0,0 +1,5 @@ +package com.ticxo.modelengine.api.utils.meta; + +public interface IMetaHolder { + MetadataRegistry getMetadata(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/meta/MetadataRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/utils/meta/MetadataRegistry.java new file mode 100644 index 0000000..e8f5d7b --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/meta/MetadataRegistry.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.api.utils.meta; + +import com.google.common.collect.Maps; +import java.util.Map; +import org.bukkit.NamespacedKey; +import org.jetbrains.annotations.Nullable; + +public class MetadataRegistry { + private final Map metadata = Maps.newConcurrentMap(); + + @Nullable + public T get(NamespacedKey key) { + return (T)this.metadata.get(key); + } + + @Nullable + public T get(String key) { + return this.get(NamespacedKey.fromString(key)); + } + + public Object put(NamespacedKey key, Object data) { + return this.metadata.put(key, data); + } + + public Object put(String key, Object data) { + return this.put(NamespacedKey.fromString(key), data); + } + + public boolean has(NamespacedKey key) { + return this.metadata.containsKey(key); + } + + public boolean has(String key) { + return this.has(NamespacedKey.fromString(key)); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/promise/AbstractFoliaPromise.java b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/AbstractFoliaPromise.java new file mode 100644 index 0000000..7d3b29e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/AbstractFoliaPromise.java @@ -0,0 +1,24 @@ +package com.ticxo.modelengine.api.utils.promise; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import java.util.concurrent.TimeUnit; +import org.bukkit.Bukkit; + +public abstract class AbstractFoliaPromise extends AbstractPromise { + protected AbstractFoliaPromise() { + } + + protected AbstractFoliaPromise(T val) { + super(val); + } + + @Override + protected final void executeAsync(Runnable runnable) { + Bukkit.getAsyncScheduler().runNow(ModelEngineAPI.getAPI(), task -> runnable.run()); + } + + @Override + protected final void executeAsync(Runnable runnable, int delay) { + Bukkit.getAsyncScheduler().runDelayed(ModelEngineAPI.getAPI(), task -> runnable.run(), delay * 50, TimeUnit.MILLISECONDS); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/promise/AbstractPromise.java b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/AbstractPromise.java new file mode 100644 index 0000000..c068434 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/AbstractPromise.java @@ -0,0 +1,133 @@ +package com.ticxo.modelengine.api.utils.promise; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Function; +import java.util.function.Supplier; +import org.jetbrains.annotations.NotNull; + +public abstract class AbstractPromise implements Promise { + @NotNull + private final CompletableFuture future; + + protected AbstractPromise() { + this.future = new CompletableFuture<>(); + } + + protected AbstractPromise(T val) { + this.future = CompletableFuture.completedFuture(val); + } + + @Override + public Promise runSync(Runnable runnable) { + this.executeSync(runnable); + return this; + } + + @Override + public Promise runSyncDelay(Runnable runnable, int delay) { + this.executeSync(runnable, delay); + return this; + } + + @Override + public Promise runAsync(Runnable runnable) { + this.executeAsync(runnable); + return this; + } + + @Override + public Promise runAsyncDelay(Runnable runnable, int delay) { + this.executeAsync(runnable, delay); + return this; + } + + @Override + public Promise supplySync(Supplier supplier) { + this.executeSync(() -> this.future.complete(supplier.get())); + return this; + } + + @Override + public Promise supplySyncDelay(Supplier supplier, int delay) { + this.executeSync(() -> this.future.complete(supplier.get()), delay); + return this; + } + + @Override + public Promise supplyAsync(Supplier supplier) { + this.executeAsync(() -> this.future.complete(supplier.get())); + return this; + } + + @Override + public Promise supplyAsyncDelay(Supplier supplier, int delay) { + this.executeAsync(() -> this.future.complete(supplier.get()), delay); + return this; + } + + @Override + public Promise thenApplySync(Function function) { + AbstractPromise promise = this.createEmpty(); + this.future.whenComplete((t, throwable) -> promise.executeSync(() -> promise.future.complete((U)function.apply(t)))); + return promise; + } + + @Override + public Promise thenApplySyncDelay(Function function, int delay) { + AbstractPromise promise = this.createEmpty(); + this.future.whenComplete((t, throwable) -> promise.executeSync(() -> promise.future.complete((U)function.apply((T)t)), delay)); + return promise; + } + + @Override + public Promise thenApplyAsync(Function function) { + AbstractPromise promise = this.createEmpty(); + this.future.whenComplete((t, throwable) -> promise.executeAsync(() -> promise.future.complete((U)function.apply(t)))); + return promise; + } + + @Override + public Promise thenApplyAsyncDelay(Function function, int delay) { + AbstractPromise promise = this.createEmpty(); + this.future.whenComplete((t, throwable) -> promise.executeAsync(() -> promise.future.complete((U)function.apply((T)t)), delay)); + return promise; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return this.future.cancel(mayInterruptIfRunning); + } + + @Override + public boolean isCancelled() { + return this.future.isCancelled(); + } + + @Override + public boolean isDone() { + return this.future.isDone(); + } + + @Override + public T get() throws InterruptedException, ExecutionException { + return this.future.get(); + } + + @Override + public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return this.future.get(timeout, unit); + } + + protected abstract AbstractPromise createEmpty(); + + protected abstract void executeSync(Runnable var1); + + protected abstract void executeSync(Runnable var1, int var2); + + protected abstract void executeAsync(Runnable var1); + + protected abstract void executeAsync(Runnable var1, int var2); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/promise/EntityPromise.java b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/EntityPromise.java new file mode 100644 index 0000000..303793a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/EntityPromise.java @@ -0,0 +1,40 @@ +package com.ticxo.modelengine.api.utils.promise; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import org.bukkit.entity.Entity; + +public class EntityPromise extends AbstractFoliaPromise { + private final Entity entity; + + private EntityPromise(Entity entity) { + this.entity = entity; + } + + private EntityPromise(Entity entity, T val) { + super(val); + this.entity = entity; + } + + @Override + protected AbstractPromise createEmpty() { + return empty(this.entity); + } + + @Override + protected void executeSync(Runnable runnable) { + this.entity.getScheduler().execute(ModelEngineAPI.getAPI(), runnable, null, 0L); + } + + @Override + protected void executeSync(Runnable runnable, int delay) { + this.entity.getScheduler().execute(ModelEngineAPI.getAPI(), runnable, null, delay); + } + + static EntityPromise empty(Entity entity) { + return new EntityPromise<>(entity); + } + + static EntityPromise completed(Entity entity, T val) { + return new EntityPromise<>(entity, val); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/promise/GlobalPromise.java b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/GlobalPromise.java new file mode 100644 index 0000000..ac74008 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/GlobalPromise.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.api.utils.promise; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import org.bukkit.Bukkit; + +public class GlobalPromise extends AbstractFoliaPromise { + private GlobalPromise() { + } + + private GlobalPromise(T val) { + super(val); + } + + @Override + protected AbstractPromise createEmpty() { + return empty(); + } + + @Override + protected void executeSync(Runnable runnable) { + Bukkit.getGlobalRegionScheduler().execute(ModelEngineAPI.getAPI(), runnable); + } + + @Override + protected void executeSync(Runnable runnable, int delay) { + Bukkit.getGlobalRegionScheduler().runDelayed(ModelEngineAPI.getAPI(), task -> runnable.run(), delay); + } + + static GlobalPromise empty() { + return new GlobalPromise<>(); + } + + static GlobalPromise completed(T val) { + return new GlobalPromise<>(val); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/promise/LegacyPromise.java b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/LegacyPromise.java new file mode 100644 index 0000000..8f3bf77 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/LegacyPromise.java @@ -0,0 +1,54 @@ +package com.ticxo.modelengine.api.utils.promise; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import org.bukkit.Bukkit; + +public class LegacyPromise extends AbstractPromise { + private LegacyPromise() { + } + + private LegacyPromise(T val) { + super(val); + } + + @Override + protected AbstractPromise createEmpty() { + return empty(); + } + + @Override + protected void executeSync(Runnable runnable) { + if (Bukkit.isPrimaryThread()) { + runnable.run(); + } else { + Bukkit.getScheduler().runTask(ModelEngineAPI.getAPI(), runnable); + } + } + + @Override + protected void executeSync(Runnable runnable, int delay) { + Bukkit.getScheduler().runTaskLater(ModelEngineAPI.getAPI(), runnable, delay); + } + + @Override + protected void executeAsync(Runnable runnable) { + if (Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTaskAsynchronously(ModelEngineAPI.getAPI(), runnable); + } else { + runnable.run(); + } + } + + @Override + protected void executeAsync(Runnable runnable, int delay) { + Bukkit.getScheduler().runTaskLaterAsynchronously(ModelEngineAPI.getAPI(), runnable, delay); + } + + static LegacyPromise empty() { + return new LegacyPromise<>(); + } + + static LegacyPromise completed(T val) { + return new LegacyPromise<>(val); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/promise/Promise.java b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/Promise.java new file mode 100644 index 0000000..d404c53 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/Promise.java @@ -0,0 +1,168 @@ +package com.ticxo.modelengine.api.utils.promise; + +import com.ticxo.modelengine.api.ServerInfo; +import java.util.concurrent.Future; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.jetbrains.annotations.Nullable; + +public interface Promise extends Future { + static Promise empty() { + return (Promise)(ServerInfo.IS_FOLIA ? GlobalPromise.empty() : LegacyPromise.empty()); + } + + static Promise empty(Entity entity) { + return (Promise)(ServerInfo.IS_FOLIA ? EntityPromise.empty(entity) : empty()); + } + + static Promise empty(Location location) { + return (Promise)(ServerInfo.IS_FOLIA ? RegionPromise.empty(location) : empty()); + } + + static Promise start() { + return ServerInfo.IS_FOLIA ? GlobalPromise.completed(null) : LegacyPromise.completed(null); + } + + static Promise start(Entity entity) { + return (Promise)(ServerInfo.IS_FOLIA ? EntityPromise.completed(entity, null) : start()); + } + + static Promise start(Location location) { + return (Promise)(ServerInfo.IS_FOLIA ? RegionPromise.completed(location, null) : start()); + } + + static Promise completed(@Nullable U value) { + return (Promise)(ServerInfo.IS_FOLIA ? GlobalPromise.completed(value) : LegacyPromise.completed(value)); + } + + static Promise completed(Entity entity, @Nullable U value) { + return (Promise)(ServerInfo.IS_FOLIA ? EntityPromise.completed(entity, value) : completed(value)); + } + + static Promise completed(Location location, @Nullable U value) { + return (Promise)(ServerInfo.IS_FOLIA ? RegionPromise.completed(location, value) : completed(value)); + } + + static Promise supplyingSync(Supplier supplier) { + Promise promise = empty(); + return promise.supplySync(supplier); + } + + static Promise supplyingSync(Entity entity, Supplier supplier) { + Promise promise = empty(entity); + return promise.supplySync(supplier); + } + + static Promise supplyingSync(Location location, Supplier supplier) { + Promise promise = empty(location); + return promise.supplySync(supplier); + } + + static Promise supplyingSyncDelay(Supplier supplier, int delay) { + Promise promise = empty(); + return promise.supplySyncDelay(supplier, delay); + } + + static Promise supplyingSyncDelay(Entity entity, Supplier supplier, int delay) { + Promise promise = empty(entity); + return promise.supplySyncDelay(supplier, delay); + } + + static Promise supplyingSyncDelay(Location location, Supplier supplier, int delay) { + Promise promise = empty(location); + return promise.supplySyncDelay(supplier, delay); + } + + static Promise supplyingAsync(Supplier supplier) { + Promise promise = empty(); + return promise.supplyAsync(supplier); + } + + static Promise supplyingAsyncDelay(Supplier supplier, int delay) { + Promise promise = empty(); + return promise.supplyAsyncDelay(supplier, delay); + } + + Promise runSync(Runnable var1); + + Promise runSyncDelay(Runnable var1, int var2); + + Promise runAsync(Runnable var1); + + Promise runAsyncDelay(Runnable var1, int var2); + + Promise supplySync(Supplier var1); + + Promise supplySyncDelay(Supplier var1, int var2); + + Promise supplyAsync(Supplier var1); + + Promise supplyAsyncDelay(Supplier var1, int var2); + + default Promise thenRunSync(Runnable runnable) { + return this.thenApplySync(t -> { + runnable.run(); + return null; + }); + } + + default Promise thenRunSyncDelay(Runnable runnable, int delay) { + return this.thenApplySyncDelay(t -> { + runnable.run(); + return null; + }, delay); + } + + default Promise thenRunAsync(Runnable runnable) { + return this.thenApplyAsync(t -> { + runnable.run(); + return null; + }); + } + + default Promise thenRunAsyncDelay(Runnable runnable, int delay) { + return this.thenApplyAsyncDelay(t -> { + runnable.run(); + return null; + }, delay); + } + + Promise thenApplySync(Function var1); + + Promise thenApplySyncDelay(Function var1, int var2); + + Promise thenApplyAsync(Function var1); + + Promise thenApplyAsyncDelay(Function var1, int var2); + + default Promise thenAcceptSync(Consumer consumer) { + return this.thenApplySync(t -> { + consumer.accept(t); + return null; + }); + } + + default Promise thenAcceptSyncDelay(Consumer consumer, int delay) { + return this.thenApplySyncDelay(t -> { + consumer.accept(t); + return null; + }, delay); + } + + default Promise thenAcceptAsync(Consumer consumer) { + return this.thenApplyAsync(t -> { + consumer.accept(t); + return null; + }); + } + + default Promise thenAcceptAsyncDelay(Consumer consumer, int delay) { + return this.thenApplyAsyncDelay(t -> { + consumer.accept(t); + return null; + }, delay); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/promise/RegionPromise.java b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/RegionPromise.java new file mode 100644 index 0000000..7f30eda --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/promise/RegionPromise.java @@ -0,0 +1,41 @@ +package com.ticxo.modelengine.api.utils.promise; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import org.bukkit.Bukkit; +import org.bukkit.Location; + +public class RegionPromise extends AbstractFoliaPromise { + private final Location location; + + private RegionPromise(Location location) { + this.location = location; + } + + private RegionPromise(Location location, T val) { + super(val); + this.location = location; + } + + @Override + protected AbstractPromise createEmpty() { + return empty(this.location); + } + + @Override + protected void executeSync(Runnable runnable) { + Bukkit.getRegionScheduler().execute(ModelEngineAPI.getAPI(), this.location, runnable); + } + + @Override + protected void executeSync(Runnable runnable, int delay) { + Bukkit.getRegionScheduler().runDelayed(ModelEngineAPI.getAPI(), this.location, task -> runnable.run(), delay); + } + + static RegionPromise empty(Location location) { + return new RegionPromise<>(location); + } + + static RegionPromise completed(Location location, T val) { + return new RegionPromise<>(location, val); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/registry/TRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/utils/registry/TRegistry.java new file mode 100644 index 0000000..81acb04 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/registry/TRegistry.java @@ -0,0 +1,47 @@ +package com.ticxo.modelengine.api.utils.registry; + +import com.google.common.collect.Maps; +import java.util.Collection; +import java.util.Map; +import java.util.Set; + +public abstract class TRegistry { + protected final Map registry = this.mapSupplier(); + protected T defaultItem; + + public void register(String id, T item) { + this.registry.put(id, item); + } + + public void registerAndDefault(String id, T item) { + this.registry.put(id, item); + this.defaultItem = item; + } + + public R get(String id) { + T item = this.registry.get(id); + return item == null ? this.getDefault() : this.convert(item); + } + + public R getDefault() { + return this.convert(this.defaultItem); + } + + public Set getKeys() { + return this.registry.keySet(); + } + + public Collection getValues() { + return this.registry.values(); + } + + protected abstract R convert(T var1); + + protected Map mapSupplier() { + return Maps.newConcurrentMap(); + } + + public void setDefaultItem(T defaultItem) { + this.defaultItem = defaultItem; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/registry/TUnaryRegistry.java b/api/src/main/java/com/ticxo/modelengine/api/utils/registry/TUnaryRegistry.java new file mode 100644 index 0000000..7a70742 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/registry/TUnaryRegistry.java @@ -0,0 +1,23 @@ +package com.ticxo.modelengine.api.utils.registry; + +public abstract class TUnaryRegistry extends TRegistry { + @Override + public T get(String id) { + if (id == null) { + return this.getDefault(); + } else { + T item = this.registry.get(id); + return item == null ? this.getDefault() : item; + } + } + + @Override + public T getDefault() { + return this.defaultItem; + } + + @Override + protected T convert(T item) { + return item; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/resourcepack/ResourcePackFeature.java b/api/src/main/java/com/ticxo/modelengine/api/utils/resourcepack/ResourcePackFeature.java new file mode 100644 index 0000000..f2bb294 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/resourcepack/ResourcePackFeature.java @@ -0,0 +1,7 @@ +package com.ticxo.modelengine.api.utils.resourcepack; + +public enum ResourcePackFeature { + COLORABLE_ITEM, + DATA_DRIVEN, + COMPOSITE_BYPASS; +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/resourcepack/ResourcePackVersion.java b/api/src/main/java/com/ticxo/modelengine/api/utils/resourcepack/ResourcePackVersion.java new file mode 100644 index 0000000..ea42459 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/resourcepack/ResourcePackVersion.java @@ -0,0 +1,61 @@ +package com.ticxo.modelengine.api.utils.resourcepack; + +import java.util.Set; + +public enum ResourcePackVersion { + v1_19_4(13, ResourcePackFeature.COLORABLE_ITEM), + v1_20(15, ResourcePackFeature.COLORABLE_ITEM), + v1_20_1(15, ResourcePackFeature.COLORABLE_ITEM), + v1_20_2(18, ResourcePackFeature.COLORABLE_ITEM), + v1_20_3(22, ResourcePackFeature.COLORABLE_ITEM), + v1_20_4(22, ResourcePackFeature.COLORABLE_ITEM), + v1_20_5(32, ResourcePackFeature.COLORABLE_ITEM), + v1_20_6(32, ResourcePackFeature.COLORABLE_ITEM), + v1_21(34, ResourcePackFeature.COLORABLE_ITEM), + v1_21_1(34, ResourcePackFeature.COLORABLE_ITEM), + v1_21_2(42, ResourcePackFeature.COLORABLE_ITEM), + v1_21_3(42, ResourcePackFeature.COLORABLE_ITEM), + v1_21_4(46, ResourcePackFeature.COLORABLE_ITEM, ResourcePackFeature.DATA_DRIVEN, ResourcePackFeature.COMPOSITE_BYPASS); + + private final int version; + private final Set availableFeatures; + + private ResourcePackVersion(int version, ResourcePackFeature... features) { + this.version = version; + this.availableFeatures = Set.of(features); + } + + public static ResourcePackVersion getVersion(String value) { + if (!value.startsWith("1_")) { + value = "1_" + value; + } + + if (!value.startsWith("v")) { + value = "v" + value; + } + + value = value.replaceAll("\\.", "_"); + if (value.endsWith("_0")) { + value = value.substring(0, value.length() - 2); + } + + return get(value); + } + + public static ResourcePackVersion get(String value) { + try { + return valueOf(value); + } catch (IllegalArgumentException var2) { + var2.printStackTrace(); + return v1_19_4; + } + } + + public int getVersion() { + return this.version; + } + + public Set getAvailableFeatures() { + return this.availableFeatures; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/BukkitPlatformScheduler.java b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/BukkitPlatformScheduler.java new file mode 100644 index 0000000..ddcf4c5 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/BukkitPlatformScheduler.java @@ -0,0 +1,28 @@ +package com.ticxo.modelengine.api.utils.scheduling; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.plugin.Plugin; + +public class BukkitPlatformScheduler implements PlatformScheduler { + @Override + public PlatformTask scheduleRepeating(Plugin plugin, Runnable task, long delay, long period) { + return new BukkitPlatformTask(Bukkit.getScheduler().runTaskTimer(plugin, task, delay, period)); + } + + @Override + public PlatformTask scheduleRepeating(Plugin plugin, Entity entity, Runnable task, long delay, long period) { + return this.scheduleRepeating(plugin, task, delay, period); + } + + @Override + public PlatformTask scheduleRepeating(Plugin plugin, Location location, Runnable task, long delay, long period) { + return this.scheduleRepeating(plugin, task, delay, period); + } + + @Override + public PlatformTask scheduleRepeatingAsync(Plugin plugin, Runnable task, long delay, long period) { + return new BukkitPlatformTask(Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, task, delay, period)); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/BukkitPlatformTask.java b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/BukkitPlatformTask.java new file mode 100644 index 0000000..f89bf81 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/BukkitPlatformTask.java @@ -0,0 +1,16 @@ +package com.ticxo.modelengine.api.utils.scheduling; + +import org.bukkit.scheduler.BukkitTask; + +public class BukkitPlatformTask implements PlatformTask { + protected BukkitTask task; + + public BukkitPlatformTask(BukkitTask task) { + this.task = task; + } + + @Override + public void cancel() { + this.task.cancel(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/FoliaPlatformScheduler.java b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/FoliaPlatformScheduler.java new file mode 100644 index 0000000..2ca873a --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/FoliaPlatformScheduler.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.api.utils.scheduling; + +import java.util.concurrent.TimeUnit; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.plugin.Plugin; + +public class FoliaPlatformScheduler implements PlatformScheduler { + @Override + public PlatformTask scheduleRepeating(Plugin plugin, Runnable task, long delay, long period) { + return new FoliaPlatformTask(Bukkit.getGlobalRegionScheduler().runAtFixedRate(plugin, ignore -> task.run(), Math.max(1L, delay), Math.max(1L, period))); + } + + @Override + public PlatformTask scheduleRepeating(Plugin plugin, Entity entity, Runnable task, long delay, long period) { + return new FoliaPlatformTask(entity.getScheduler().runAtFixedRate(plugin, ignore -> task.run(), null, Math.max(1L, delay), Math.max(1L, period))); + } + + @Override + public PlatformTask scheduleRepeating(Plugin plugin, Location location, Runnable task, long delay, long period) { + return new FoliaPlatformTask( + Bukkit.getRegionScheduler().runAtFixedRate(plugin, location, ignore -> task.run(), Math.max(1L, delay), Math.max(1L, period)) + ); + } + + @Override + public PlatformTask scheduleRepeatingAsync(Plugin plugin, Runnable task, long delay, long period) { + return new FoliaPlatformTask( + Bukkit.getAsyncScheduler().runAtFixedRate(plugin, ignore -> task.run(), Math.max(1L, delay) * 50L, Math.max(1L, period) * 50L, TimeUnit.MILLISECONDS) + ); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/FoliaPlatformTask.java b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/FoliaPlatformTask.java new file mode 100644 index 0000000..8e03a5e --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/FoliaPlatformTask.java @@ -0,0 +1,16 @@ +package com.ticxo.modelengine.api.utils.scheduling; + +import io.papermc.paper.threadedregions.scheduler.ScheduledTask; + +public class FoliaPlatformTask implements PlatformTask { + protected ScheduledTask task; + + public FoliaPlatformTask(ScheduledTask task) { + this.task = task; + } + + @Override + public void cancel() { + this.task.cancel(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/PlatformScheduler.java b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/PlatformScheduler.java new file mode 100644 index 0000000..47f4e23 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/PlatformScheduler.java @@ -0,0 +1,15 @@ +package com.ticxo.modelengine.api.utils.scheduling; + +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.plugin.Plugin; + +public interface PlatformScheduler { + PlatformTask scheduleRepeating(Plugin var1, Runnable var2, long var3, long var5); + + PlatformTask scheduleRepeating(Plugin var1, Entity var2, Runnable var3, long var4, long var6); + + PlatformTask scheduleRepeating(Plugin var1, Location var2, Runnable var3, long var4, long var6); + + PlatformTask scheduleRepeatingAsync(Plugin var1, Runnable var2, long var3, long var5); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/PlatformTask.java b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/PlatformTask.java new file mode 100644 index 0000000..733d0a1 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/scheduling/PlatformTask.java @@ -0,0 +1,5 @@ +package com.ticxo.modelengine.api.utils.scheduling; + +public interface PlatformTask { + void cancel(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/state/StateMachine.java b/api/src/main/java/com/ticxo/modelengine/api/utils/state/StateMachine.java new file mode 100644 index 0000000..cc85166 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/state/StateMachine.java @@ -0,0 +1,56 @@ +package com.ticxo.modelengine.api.utils.state; + +import java.util.function.Function; + +public class StateMachine { + protected StateNode currentNode; + + public void setEntryNode(StateNode entryNode) { + this.currentNode = entryNode; + } + + public StateNode createNode() { + return new StateNode<>(this); + } + + public void execute(T target) { + if (this.currentNode == null) { + this.currentNode = this.getCurrentNode(); + } + + if (this.currentNode != null) { + boolean updated = false; + + for (Function> processor : this.currentNode.getForceConnected()) { + StateNode node = processor.apply(target); + if (node != null) { + this.currentNode.acceptExit(target); + this.currentNode = node; + this.currentNode.acceptEntry(target); + updated = true; + break; + } + } + + if (!updated && this.currentNode.testCommonPredicate(target)) { + for (Function> processorx : this.currentNode.getConnected()) { + StateNode node = processorx.apply(target); + if (node != null) { + this.currentNode.acceptExit(target); + this.currentNode = node; + this.currentNode.acceptEntry(target); + break; + } + } + } + + if (this.currentNode != null) { + this.currentNode.acceptAction(target); + } + } + } + + public StateNode getCurrentNode() { + return this.currentNode; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/state/StateNode.java b/api/src/main/java/com/ticxo/modelengine/api/utils/state/StateNode.java new file mode 100644 index 0000000..b766ebb --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/state/StateNode.java @@ -0,0 +1,146 @@ +package com.ticxo.modelengine.api.utils.state; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; + +public class StateNode { + private final StateMachine machine; + private final List>> forceConnected = new ArrayList<>(); + private final List>> connected = new ArrayList<>(); + private Consumer entryAction; + private Consumer action; + private Consumer exitAction; + private Predicate commonPredicate; + private Predicate entryPredicate; + + public void addForceConnectedNode(Predicate condition, StateNode node) { + this.addForceConnectedNode(condition, t -> node); + } + + public void addForceConnectedNode(Predicate condition, Function> node) { + this.addForceNodeProcessor(t -> { + if (!condition.test(t)) { + return null; + } else { + StateNode n = node.apply(t); + return n.testEntryPredicate(t) ? n : null; + } + }); + } + + public void addForceNodeProcessor(Function> node) { + this.forceConnected.add(node); + } + + public void clearForceConnectedNodes() { + this.forceConnected.clear(); + } + + public void addConnectedNode(Predicate condition, StateNode node) { + this.addConnectedNode(condition, t -> node); + } + + public void addConnectedNode(Predicate condition, Function> node) { + this.addNodeProcessor(t -> { + if (!condition.test(t)) { + return null; + } else { + StateNode n = node.apply(t); + return n.testEntryPredicate(t) ? n : null; + } + }); + } + + public void addNodeProcessor(Function> node) { + this.connected.add(node); + } + + public void clearConnectedNodes() { + this.connected.clear(); + } + + public void acceptAction(T target) { + if (this.action != null) { + this.action.accept(target); + } + } + + public void acceptEntry(T target) { + if (this.entryAction != null) { + this.entryAction.accept(target); + } + } + + public void acceptExit(T target) { + if (this.exitAction != null) { + this.exitAction.accept(target); + } + } + + public boolean testCommonPredicate(T target) { + return this.commonPredicate == null || this.commonPredicate.test(target); + } + + public boolean testEntryPredicate(T target) { + return this.entryPredicate == null || this.entryPredicate.test(target); + } + + public StateNode(StateMachine machine) { + this.machine = machine; + } + + public StateMachine getMachine() { + return this.machine; + } + + public List>> getForceConnected() { + return this.forceConnected; + } + + public List>> getConnected() { + return this.connected; + } + + public Consumer getEntryAction() { + return this.entryAction; + } + + public Consumer getAction() { + return this.action; + } + + public Consumer getExitAction() { + return this.exitAction; + } + + public Predicate getCommonPredicate() { + return this.commonPredicate; + } + + public Predicate getEntryPredicate() { + return this.entryPredicate; + } + + public void setEntryAction(Consumer entryAction) { + this.entryAction = entryAction; + } + + public void setAction(Consumer action) { + this.action = action; + } + + public void setExitAction(Consumer exitAction) { + this.exitAction = exitAction; + } + + public void setCommonPredicate(Predicate commonPredicate) { + this.commonPredicate = commonPredicate; + } + + public void setEntryPredicate(Predicate entryPredicate) { + this.entryPredicate = entryPredicate; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/AbstractLoadBalancer.java b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/AbstractLoadBalancer.java new file mode 100644 index 0000000..5c74b16 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/AbstractLoadBalancer.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.api.utils.ticker; + +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiConsumer; + +public abstract class AbstractLoadBalancer implements LoadBalancer { + protected final Set available = ConcurrentHashMap.newKeySet(); + protected final Map reference = new ConcurrentHashMap<>(); + + public AbstractLoadBalancer(int counts) { + if (counts <= 0) { + throw new RuntimeException("Cannot create load balancer with less than 1 server: " + counts); + } else { + for (int i = 0; i < counts; i++) { + this.available.add(this.supply()); + } + } + } + + @Override + public SER getOrRegister(KEY key) { + SER current = this.reference.get(key); + if (current != null) { + return current; + } else { + int load = Integer.MAX_VALUE; + SER leastLoad = null; + + for (SER server : this.available) { + if (server.getLoad() < load) { + leastLoad = server; + load = server.getLoad(); + } + } + + if (leastLoad == null) { + throw new RuntimeException("No server found."); + } else { + this.reference.put(key, leastLoad); + return leastLoad; + } + } + } + + @Override + public SER get(KEY key) { + return this.reference.get(key); + } + + @Override + public void unregister(KEY key) { + this.reference.remove(key); + } + + @Override + public void execute(KEY key, BiConsumer balConsumer) { + balConsumer.accept(key, this.getOrRegister(key)); + } + + public Set getAvailable() { + return this.available; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/AsyncTaskExecutor.java b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/AsyncTaskExecutor.java new file mode 100644 index 0000000..e42f3ee --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/AsyncTaskExecutor.java @@ -0,0 +1,31 @@ +package com.ticxo.modelengine.api.utils.ticker; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class AsyncTaskExecutor { + private final ExecutorService executor; + private final List> futures = new ArrayList<>(); + + public AsyncTaskExecutor() { + this.executor = Executors.newWorkStealingPool(); + } + + public AsyncTaskExecutor(int threads) { + this.executor = Executors.newWorkStealingPool(threads); + } + + public CompletableFuture run(Runnable runnable) { + CompletableFuture future = CompletableFuture.runAsync(runnable, this.executor); + this.futures.add(future); + return future; + } + + public void join() { + CompletableFuture.allOf(this.futures.toArray(CompletableFuture[]::new)).join(); + this.futures.clear(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/DualTicker.java b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/DualTicker.java new file mode 100644 index 0000000..865ffe6 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/DualTicker.java @@ -0,0 +1,82 @@ +package com.ticxo.modelengine.api.utils.ticker; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.utils.scheduling.PlatformScheduler; +import java.util.function.Consumer; +import org.bukkit.plugin.java.JavaPlugin; + +public class DualTicker { + private final PseudoThread sync; + private final PseudoThread async; + + public DualTicker(JavaPlugin plugin, PlatformScheduler scheduler) { + this.sync = new PseudoThread("sync", scheduler, plugin, false, 0, 0, false, false); + this.async = new PseudoThread("async", scheduler, plugin, true, 0, 0, false, false); + } + + public static void queueSyncTask(Runnable runnable) { + queueDelayedSyncTask(task -> runnable.run(), 0); + } + + public static void queueDelayedSyncTask(Runnable runnable, int delay) { + queueDelayedSyncTask(task -> runnable.run(), delay); + } + + public static void queueRepeatingSyncTask(Runnable runnable, int delay, int interval) { + queueRepeatingSyncTask(task -> runnable.run(), delay, interval); + } + + public static void queueSyncTask(Consumer consumer) { + queueDelayedSyncTask(consumer, 0); + } + + public static void queueDelayedSyncTask(Consumer consumer, int delay) { + DualTicker ticker = ModelEngineAPI.getAPI().getTicker(); + ticker.sync.queueTask(new Task(consumer, delay, 0, false)); + } + + public static void queueRepeatingSyncTask(Consumer consumer, int delay, int interval) { + DualTicker ticker = ModelEngineAPI.getAPI().getTicker(); + ticker.sync.queueTask(new Task(consumer, delay, interval, true)); + } + + public static void queueAsyncTask(Runnable runnable) { + queueDelayedAsyncTask(task -> runnable.run(), 0); + } + + public static void queueDelayedAsyncTask(Runnable runnable, int delay) { + queueDelayedAsyncTask(task -> runnable.run(), delay); + } + + public static void queueRepeatingAsyncTask(Runnable runnable, int delay, int interval) { + queueRepeatingAsyncTask(task -> runnable.run(), delay, interval); + } + + public static void queueAsyncTask(Consumer consumer) { + queueDelayedAsyncTask(consumer, 0); + } + + public static void queueDelayedAsyncTask(Consumer consumer, int delay) { + DualTicker ticker = ModelEngineAPI.getAPI().getTicker(); + ticker.async.queueTask(new Task(consumer, delay, 0, false)); + } + + public static void queueRepeatingAsyncTask(Consumer consumer, int delay, int interval) { + DualTicker ticker = ModelEngineAPI.getAPI().getTicker(); + ticker.async.queueTask(new Task(consumer, delay, interval, true)); + } + + public void start() { + this.sync.start(); + this.async.start(); + ModelEngineAPI.getAPI().getDataTrackers().start(); + ModelEngineAPI.getAPI().getModelUpdaters().start(); + } + + public void stop() { + this.sync.end(); + this.async.end(); + ModelEngineAPI.getAPI().getDataTrackers().end(); + ModelEngineAPI.getAPI().getModelUpdaters().end(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/LoadBalancer.java b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/LoadBalancer.java new file mode 100644 index 0000000..4eabbc5 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/LoadBalancer.java @@ -0,0 +1,24 @@ +package com.ticxo.modelengine.api.utils.ticker; + +import java.util.function.BiConsumer; +import java.util.function.Function; + +public interface LoadBalancer { + SER getOrRegister(KEY var1); + + SER get(KEY var1); + + void unregister(KEY var1); + + void execute(KEY var1, BiConsumer var2); + + SER supply(); + + default VAL map(KEY key, Function mapper) { + return mapper.apply(this.getOrRegister(key)); + } + + public interface Server { + int getLoad(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/PseudoThread.java b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/PseudoThread.java new file mode 100644 index 0000000..538d0ce --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/PseudoThread.java @@ -0,0 +1,115 @@ +package com.ticxo.modelengine.api.utils.ticker; + +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.scheduling.PlatformScheduler; +import com.ticxo.modelengine.api.utils.scheduling.PlatformTask; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.function.Consumer; +import org.bukkit.plugin.java.JavaPlugin; + +public class PseudoThread { + private final String name; + private final PlatformScheduler scheduler; + private final JavaPlugin plugin; + private final boolean isAsync; + private final int delay; + private final int period; + private final boolean canWait; + private final boolean canMultiTick; + private final Queue taskQueue = new ConcurrentLinkedQueue<>(); + private final List tasks = new ArrayList<>(); + private final List> overloadCallback = new ArrayList<>(); + private PlatformTask tickTask; + private boolean locked; + private int skipped; + private long lastTick = System.nanoTime(); + + public void start() { + if (this.isAsync) { + this.tickTask = this.scheduler.scheduleRepeatingAsync(this.plugin, this::tick, this.delay, this.period); + } else { + this.tickTask = this.scheduler.scheduleRepeating(this.plugin, this::tick, this.delay, this.period); + } + } + + public void end() { + this.taskQueue.clear(); + this.tasks.clear(); + if (this.tickTask != null) { + this.tickTask.cancel(); + } + } + + public void queueTask(Task task) { + this.taskQueue.add(task); + } + + public void registerOverloadCallback(Consumer callback) { + this.overloadCallback.add(callback); + } + + private void tick() { + long currentTick = System.currentTimeMillis(); + long nowNanos = System.nanoTime(); + if (this.canMultiTick || nowNanos - this.lastTick >= 45000000L) { + this.lastTick = nowNanos; + if (this.locked) { + this.skipped++; + } else { + this.locked = true; + + while (!this.taskQueue.isEmpty()) { + this.tasks.add(this.taskQueue.poll()); + } + + this.tasks.removeIf(task -> { + try { + return task.tick(); + } catch (Throwable var2) { + var2.printStackTrace(); + return task.isCanceled() || !task.isRepeating(); + } + }); + long timings = System.currentTimeMillis() - currentTick; + this.locked = false; + if (this.skipped > 0) { + this.overloadCallback.forEach(callback -> callback.accept(this.skipped)); + if (!this.canWait) { + TLogger.debug( + "The pseudo thread [" + + this.name + + "] has skipped " + + this.skipped + + (this.skipped == 1 ? " tick" : " ticks") + + " (" + + timings + + "ms). Is it overloaded?" + ); + } + + this.skipped = 0; + } + } + } + } + + public PseudoThread( + String name, PlatformScheduler scheduler, JavaPlugin plugin, boolean isAsync, int delay, int period, boolean canWait, boolean canMultiTick + ) { + this.name = name; + this.scheduler = scheduler; + this.plugin = plugin; + this.isAsync = isAsync; + this.delay = delay; + this.period = period; + this.canWait = canWait; + this.canMultiTick = canMultiTick; + } + + public String getName() { + return this.name; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/Task.java b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/Task.java new file mode 100644 index 0000000..88e82ae --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/utils/ticker/Task.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.api.utils.ticker; + +import java.util.function.Consumer; + +public class Task { + private final Consumer task; + private final int startDelay; + private final int interval; + private final boolean isRepeating; + private int delay; + private int tick; + private int runCount; + private boolean canceled; + + public boolean tick() { + if (this.delay++ >= this.startDelay && this.tick-- <= 0) { + this.tick = this.interval; + this.task.accept(this); + this.runCount++; + return this.canceled || !this.isRepeating; + } else { + return this.canceled; + } + } + + public void cancel() { + this.canceled = true; + } + + public Task(Consumer task, int startDelay, int interval, boolean isRepeating) { + this.task = task; + this.startDelay = startDelay; + this.interval = interval; + this.isRepeating = isRepeating; + } + + public int getStartDelay() { + return this.startDelay; + } + + public int getInterval() { + return this.interval; + } + + public boolean isRepeating() { + return this.isRepeating; + } + + public int getDelay() { + return this.delay; + } + + public int getTick() { + return this.tick; + } + + public int getRunCount() { + return this.runCount; + } + + public boolean isCanceled() { + return this.canceled; + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/vfx/VFX.java b/api/src/main/java/com/ticxo/modelengine/api/vfx/VFX.java new file mode 100644 index 0000000..c882eef --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/vfx/VFX.java @@ -0,0 +1,117 @@ +package com.ticxo.modelengine.api.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import java.util.Collection; +import org.bukkit.Color; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; +import org.joml.Vector3f; + +public interface VFX { + BaseEntity getBase(); + + VFXRenderer getRenderer(); + + boolean tick(); + + void destroy(); + + boolean isInitialized(); + + boolean isDestroyed(); + + void markRemoved(); + + void queuePostInitTask(Runnable var1); + + boolean isBaseEntityVisible(); + + void setBaseEntityVisible(boolean var1); + + void setModelScale(int var1); + + float getYaw(); + + void setYaw(float var1); + + float getPitch(); + + void setPitch(float var1); + + Vector getOrigin(); + + void setOrigin(Vector var1); + + Vector3f getPosition(); + + void setPosition(Vector3f var1); + + Vector3f getRotation(); + + void setRotation(Vector3f var1); + + Vector3f getScale(); + + void setScale(Vector3f var1); + + ItemStack getModel(); + + void setModel(ItemStack var1); + + DataTracker getModelTracker(); + + Color getColor(); + + void setColor(Color var1); + + boolean isEnchanted(); + + void setEnchanted(boolean var1); + + int getBlockLight(); + + void setBlockLight(int var1); + + int getSkyLight(); + + void setSkyLight(int var1); + + default int getBrightness() { + int blockLight = this.getBlockLight(); + int skyLight = this.getSkyLight(); + if (blockLight < 0 && skyLight < 0) { + return -1; + } else { + blockLight = Math.max(blockLight, 0); + skyLight = Math.max(skyLight, 0); + return blockLight << 4 | skyLight << 20; + } + } + + boolean isVisible(); + + void setVisible(boolean var1); + + default void useModel(String modelId, String boneId) { + ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(modelId); + if (blueprint != null) { + BlueprintBone bone = blueprint.getFlatMap().get(boneId); + if (bone != null && bone.isRenderer()) { + Collection stacks = bone.getModelData().createItemStack(); + if (!stacks.isEmpty()) { + this.setModel(stacks.iterator().next()); + } + } + } + } + + default void registerSelf() { + ModelEngineAPI.getAPI().getVFXUpdater().registerVFX(this.getBase(), this); + this.getBase().registerData(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/vfx/VFXUpdater.java b/api/src/main/java/com/ticxo/modelengine/api/vfx/VFXUpdater.java new file mode 100644 index 0000000..c485fe4 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/vfx/VFXUpdater.java @@ -0,0 +1,94 @@ +package com.ticxo.modelengine.api.vfx; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import java.util.Map; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicLong; + +public class VFXUpdater { + private final Map entityIdLookup = Maps.newConcurrentMap(); + private final Map uuidLookup = Maps.newConcurrentMap(); + private final AtomicLong removalEpoch = new AtomicLong(); + + public long getRemovalEpoch() { + return this.removalEpoch.get(); + } + + public void updateAllVFXs() { + for (Entry entry : this.uuidLookup.entrySet()) { + VFX entity = entry.getValue(); + if (entity.isInitialized()) { + VFXRenderer renderer = entity.getRenderer(); + if (renderer != null) { + try { + entity.getBase().getData().asyncUpdate(); + if (!entity.tick()) { + this.removeAndDestroyVFX(entry.getKey(), entity, renderer); + } else { + renderer.sendToClient(); + entity.getBase().getData().cleanup(); + } + } catch (Throwable var6) { + var6.printStackTrace(); + this.removeAndDestroyVFX(entry.getKey(), entity, entity.getRenderer()); + } + } + } + } + } + + private void removeAndDestroyVFX(UUID uuid, VFX entity, VFXRenderer renderer) { + this.uuidLookup.remove(uuid, entity); + this.entityIdLookup.remove(entity.getBase().getEntityId(), uuid); + this.removalEpoch.incrementAndGet(); + if (renderer != null) { + try { + renderer.destroy(); + } catch (Throwable var6) { + var6.printStackTrace(); + } + } + + try { + entity.getBase().getData().cleanup(); + entity.getBase().setForcedAlive(false); + } catch (Throwable var5) { + var5.printStackTrace(); + } + + entity.destroy(); + } + + public void registerVFX(BaseEntity base, VFX vfx) { + this.entityIdLookup.put(base.getEntityId(), base.getUUID()); + this.uuidLookup.put(base.getUUID(), vfx); + } + + public VFX getVFX(int id) { + return this.getVFX(this.entityIdLookup.get(id)); + } + + public VFX getVFX(UUID uuid) { + return uuid == null ? null : this.uuidLookup.get(uuid); + } + + public VFX removeVFX(int id) { + return this.removeVFX(this.entityIdLookup.get(id)); + } + + public VFX removeVFX(UUID uuid) { + if (uuid == null) { + return null; + } else { + VFX vfx = this.uuidLookup.get(uuid); + if (vfx != null) { + vfx.markRemoved(); + } + + return vfx; + } + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXDisplayRenderer.java b/api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXDisplayRenderer.java new file mode 100644 index 0000000..0752146 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXDisplayRenderer.java @@ -0,0 +1,58 @@ +package com.ticxo.modelengine.api.vfx.render; + +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import java.util.UUID; +import org.bukkit.inventory.ItemStack; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public interface VFXDisplayRenderer extends VFXRenderer { + boolean isRespawnRequired(); + + void setRespawnRequired(boolean var1); + + VFXDisplayRenderer.VFXModel getVFXModel(); + + public interface VFXModel { + int getPivotId(); + + UUID getPivotUuid(); + + int getModelId(); + + UUID getModelUuid(); + + default PositionCodec getPositionCodec() { + return null; + } + + default void clearModelDirty() { + this.getPosition().clearDirty(); + this.getLeftRotation().clearDirty(); + this.getScale().clearDirty(); + this.getModel().clearDirty(); + this.getBrightness().clearDirty(); + } + + default boolean isModelDirty() { + return this.getPosition().isDirty() + || this.getLeftRotation().isDirty() + || this.getScale().isDirty() + || this.getModel().isDirty() + || this.getBrightness().isDirty(); + } + + DataTracker getOrigin(); + + DataTracker getPosition(); + + DataTracker getLeftRotation(); + + DataTracker getScale(); + + DataTracker getModel(); + + DataTracker getBrightness(); + } +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXRenderer.java b/api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXRenderer.java new file mode 100644 index 0000000..020884c --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXRenderer.java @@ -0,0 +1,17 @@ +package com.ticxo.modelengine.api.vfx.render; + +import com.ticxo.modelengine.api.vfx.VFX; + +public interface VFXRenderer { + VFX getVFX(); + + boolean isInitialized(); + + void initialize(); + + void readVFXData(); + + void sendToClient(); + + void destroy(); +} diff --git a/api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXRendererParser.java b/api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXRendererParser.java new file mode 100644 index 0000000..feb64f7 --- /dev/null +++ b/api/src/main/java/com/ticxo/modelengine/api/vfx/render/VFXRendererParser.java @@ -0,0 +1,7 @@ +package com.ticxo.modelengine.api.vfx.render; + +public interface VFXRendererParser { + void sendToClients(T var1); + + void destroy(T var1); +} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..5cd6b08 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,117 @@ +plugins { + java + id("io.papermc.paperweight.userdev") version "2.0.0-beta.24" apply false +} + +group = "com.ticxo.modelengine" +version = "R4.2.0" + +// Minecraft version and Java level for each NMS adapter module. +val nms = mapOf( + "v1_19_R3" to ("1.19.4-R0.1-SNAPSHOT" to 17), + "v1_20_R1" to ("1.20.1-R0.1-SNAPSHOT" to 17), + "v1_20_R2" to ("1.20.2-R0.1-SNAPSHOT" to 17), + "v1_20_R3" to ("1.20.4-R0.1-SNAPSHOT" to 17), + "v1_20_R4" to ("1.20.6-R0.1-SNAPSHOT" to 21), + "v1_21_R1" to ("1.21.1-R0.1-SNAPSHOT" to 21), + "v1_21_R2" to ("1.21.3-R0.1-SNAPSHOT" to 21), + "v1_21_R3" to ("1.21.4-R0.1-SNAPSHOT" to 21), + "v1_21_R4" to ("1.21.5-R0.1-SNAPSHOT" to 21), + "v1_21_R5" to ("1.21.8-R0.1-SNAPSHOT" to 21), + "v1_21_R6" to ("1.21.10-R0.1-SNAPSHOT" to 21), + "v1_21_R7" to ("1.21.11-R0.1-SNAPSHOT" to 21), + "v26_1" to ("26.1.2.build.74-stable" to 25), + "v26_2" to ("26.2.build.135-stable" to 25), + "v26_3" to ("26.3.build.258-stable" to 25), +) + +// Paper ran Spigot-mapped before 1.20.5 and does not remap plugins there, so these +// adapters ship reobfuscated to Spigot names; newer ones ship Mojang-mapped. +val spigotMapped = setOf("v1_19_R3", "v1_20_R1", "v1_20_R2", "v1_20_R3") + +val javaLevel = mapOf("api" to 17, "core" to 17, "core21" to 21, "core25" to 25) + + nms.mapValues { it.value.second } + +configure(subprojects.filter { it.name in javaLevel }) { + apply(plugin = "java-library") + group = rootProject.group + version = rootProject.version + + repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") + maven("https://mvn.lumine.io/repository/maven-public/") + maven("https://maven.citizensnpcs.co/repo") + maven("https://mvn.lib.co.nz/public") + maven("https://repo.viaversion.com") + maven("https://libraries.minecraft.net") + } + + // Java 17 modules are compiled with a JDK 21 toolchain targeting 17 bytecode, + // so they can read dependencies published as Java 21 class files. + val level = javaLevel.getValue(name) + extensions.configure { + // NMS modules use their exact Java level: old dev bundles only patch cleanly + // when Minecraft is decompiled on the JDK they were made with. + toolchain.languageVersion.set(JavaLanguageVersion.of(if (name in nms) level else maxOf(level, 21))) + } + tasks.withType().configureEach { + options.encoding = "UTF-8" + if (level >= 21) options.release.set(level) + else { sourceCompatibility = "$level"; targetCompatibility = "$level" } + options.compilerArgs.addAll(listOf("-Xlint:none", "-nowarn", "-Xmaxerrs", "2000")) + } + + nms[name]?.let { (bundle, _) -> + apply(plugin = "io.papermc.paperweight.userdev") + (dependencies as ExtensionAware).extensions + .getByType() + .paperDevBundle(bundle) + dependencies { + "compileOnly"(project(":api")) + } + extensions.configure { + reobfArtifactConfiguration.set( + if (name in spigotMapped) io.papermc.paperweight.userdev.ReobfArtifactConfiguration.REOBF_PRODUCTION + else io.papermc.paperweight.userdev.ReobfArtifactConfiguration.MOJANG_PRODUCTION + ) + javaLauncher.set(the().launcherFor { + languageVersion.set(JavaLanguageVersion.of(maxOf(nms.getValue(name).second, 21))) + }) + } + } +} + +// Final plugin jar: every module's classes, core resources, and the shaded jsoup/MineSkin libraries. +repositories { mavenCentral() } +val shaded by configurations.creating +dependencies { + shaded("org.jsoup:jsoup:1.17.2") { isTransitive = false } + shaded(files("libs/mineskin-java-client-3.2.1-SNAPSHOT.jar")) +} + +tasks.register("pluginJar") { + group = "build" + description = "Assembles the complete ModelEngine plugin jar." + archiveBaseName.set("ModelEngine") + archiveVersion.set(version.toString()) + destinationDirectory.set(layout.buildDirectory.dir("libs")) + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + manifest { + attributes("paperweight-mappings-namespace" to "mojang", "Multi-Release" to "true") + } + subprojects.filter { it.name in javaLevel }.forEach { p -> + if (p.name in spigotMapped) { + from(p.tasks.named("reobfJar").flatMap { it.outputJar }.map { zipTree(it) }) { + exclude("META-INF/MANIFEST.MF") + } + } else { + from(p.extensions.getByType()["main"].output) + } + } + from(shaded.map { zipTree(it) }) { + exclude("META-INF/MANIFEST.MF", "META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA", "**/module-info.class") + } +} + +tasks.named("build") { dependsOn("pluginJar") } diff --git a/core/build.gradle.kts b/core/build.gradle.kts new file mode 100644 index 0000000..df4cdf7 --- /dev/null +++ b/core/build.gradle.kts @@ -0,0 +1,10 @@ +dependencies { + compileOnly(project(":api")) + listOf("v1_19_R3", "v1_20_R1", "v1_20_R2", "v1_20_R3").forEach { compileOnly(project(":nms:$it")) } + compileOnly("io.papermc.paper:paper-api:1.20.4-R0.1-SNAPSHOT") + compileOnly("net.citizensnpcs:citizens-main:2.0.44-SNAPSHOT") { isTransitive = false } + compileOnly("me.libraryaddict.disguises:libsdisguises:26.11.10") { isTransitive = false } + compileOnly("com.viaversion:viaversion-api:5.12.2") { isTransitive = false } + compileOnly("org.jsoup:jsoup:1.17.2") + compileOnly(files("${rootDir}/libs/mineskin-java-client-3.2.1-SNAPSHOT.jar")) +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/ModelEngine.java b/core/src/main/java/com/ticxo/modelengine/core/ModelEngine.java new file mode 100644 index 0000000..47abc02 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/ModelEngine.java @@ -0,0 +1,428 @@ +package com.ticxo.modelengine.core; + +import com.google.gson.GsonBuilder; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.animation.AnimationHandlerRegistry; +import com.ticxo.modelengine.api.animation.AnimationPropertyRegistry; +import com.ticxo.modelengine.api.animation.ModelState; +import com.ticxo.modelengine.api.animation.handler.AnimationHandler; +import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypeRegistry; +import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypes; +import com.ticxo.modelengine.api.animation.keyframe.data.KeyframeReaderRegistry; +import com.ticxo.modelengine.api.animation.property.SimpleProperty; +import com.ticxo.modelengine.api.animation.script.ScriptReaderRegistry; +import com.ticxo.modelengine.api.command.AbstractCommand; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.EntityDataTrackers; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.AbstractEntityData; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.menu.ScreenManager; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelRegistry; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorRegistry; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.render.DefaultRenderType; +import com.ticxo.modelengine.api.model.bone.type.PlayerLimb; +import com.ticxo.modelengine.api.model.limb.UserLimbRegistry; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.mount.MountControllerTypeRegistry; +import com.ticxo.modelengine.api.mount.MountPairManager; +import com.ticxo.modelengine.api.mount.controller.MountControllerTypes; +import com.ticxo.modelengine.api.utils.CompatibilityManager; +import com.ticxo.modelengine.api.utils.TFile; +import com.ticxo.modelengine.api.utils.config.ConfigCache; +import com.ticxo.modelengine.api.utils.config.ConfigManager; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.scheduling.BukkitPlatformScheduler; +import com.ticxo.modelengine.api.utils.scheduling.FoliaPlatformScheduler; +import com.ticxo.modelengine.api.utils.scheduling.PlatformScheduler; +import com.ticxo.modelengine.api.utils.ticker.DualTicker; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.api.vfx.VFXUpdater; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.core.animation.handler.PriorityHandler; +import com.ticxo.modelengine.core.animation.handler.StateMachineHandler; +import com.ticxo.modelengine.core.animation.script.ModelEngineScriptReader; +import com.ticxo.modelengine.core.citizens.CitizensCommand; +import com.ticxo.modelengine.core.citizens.ModelTrait; +import com.ticxo.modelengine.core.command.MECommand; +import com.ticxo.modelengine.core.generator.ModelGeneratorImpl; +import com.ticxo.modelengine.core.generator.skin.MineSkinGeneratorService; +import com.ticxo.modelengine.core.generator.skin.SkinSplitterImpl; +import com.ticxo.modelengine.core.javasupport.Java21Access; +import com.ticxo.modelengine.core.javasupport.Java25Access; +import com.ticxo.modelengine.core.libsdisguises.DisguiseCompatibility; +import com.ticxo.modelengine.core.listener.ChatListener; +import com.ticxo.modelengine.core.listener.EntityListener; +import com.ticxo.modelengine.core.listener.InventoryListener; +import com.ticxo.modelengine.core.listener.PlayerListener; +import com.ticxo.modelengine.core.listener.WorldListener; +import com.ticxo.modelengine.core.model.ActiveModelImpl; +import com.ticxo.modelengine.core.model.ModeledEntityImpl; +import com.ticxo.modelengine.core.model.bone.behavior.GhostImpl; +import com.ticxo.modelengine.core.model.bone.behavior.HeadForcedImpl; +import com.ticxo.modelengine.core.model.bone.behavior.HeadImpl; +import com.ticxo.modelengine.core.model.bone.behavior.HeldItemImpl; +import com.ticxo.modelengine.core.model.bone.behavior.LeashImpl; +import com.ticxo.modelengine.core.model.bone.behavior.MountImpl; +import com.ticxo.modelengine.core.model.bone.behavior.NameTagImpl; +import com.ticxo.modelengine.core.model.bone.behavior.PlayerLimbImpl; +import com.ticxo.modelengine.core.model.bone.behavior.SegmentImpl; +import com.ticxo.modelengine.core.model.bone.behavior.SubHitboxImpl; +import com.ticxo.modelengine.core.model.bone.behavior.TailImpl; +import com.ticxo.modelengine.core.model.bone.behavior.UserLimbImpl; +import com.ticxo.modelengine.core.model.bone.manager.LeashManagerImpl; +import com.ticxo.modelengine.core.model.bone.manager.MountManagerImpl; +import com.ticxo.modelengine.core.model.bone.render.HeldItemRendererImpl; +import com.ticxo.modelengine.core.model.bone.render.LeashRendererImpl; +import com.ticxo.modelengine.core.model.bone.render.MountRendererImpl; +import com.ticxo.modelengine.core.model.bone.render.NameTagRendererImpl; +import com.ticxo.modelengine.core.model.bone.render.SegmentRendererImpl; +import com.ticxo.modelengine.core.model.bone.render.SubHitboxRendererImpl; +import com.ticxo.modelengine.core.vfx.VFXImpl; +import com.ticxo.modelengine.v1_19_R3.NMSHandler_v1_19_R3; +import com.ticxo.modelengine.v1_20_R1.NMSHandler_v1_20_R1; +import com.ticxo.modelengine.v1_20_R2.NMSHandler_v1_20_R2; +import com.ticxo.modelengine.v1_20_R3.NMSHandler_v1_20_R3; +import com.viaversion.viaversion.api.Via; +import java.io.File; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.Function; +import net.citizensnpcs.api.CitizensAPI; +import net.citizensnpcs.api.trait.TraitInfo; +import org.bukkit.Bukkit; +import org.bukkit.command.PluginCommand; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.joml.Vector3f; + +public class ModelEngine extends ModelEngineAPI { + public static ModelEngine CORE; + private AbstractCommand commandRoot; + private PluginManager pluginManager; + private DisguiseCompatibility disguiseCompatibility; + + public void onLoad() { + ModelEngineAPI.API = this; + CORE = this; + TLogger.logger = this.getLogger(); + this.pluginManager = Bukkit.getPluginManager(); + } + + public void onEnable() { + this.configureConfig(); + this.configureNMSHandler(); + this.gson = new GsonBuilder().create(); + this.scheduler = (PlatformScheduler)(ServerInfo.IS_FOLIA ? new FoliaPlatformScheduler() : new BukkitPlatformScheduler()); + this.modelRegistry = new ModelRegistry(); + this.modelGenerator = new ModelGeneratorImpl(this); + this.configureKeyframeTypeRegistry(); + this.keyframeReaderRegistry = new KeyframeReaderRegistry(); + this.configureScriptReaderRegistry(); + this.configureBoneBehaviorRegistry(); + this.configureTicker(); + this.configureMountControllerTypeRegistry(); + this.configureAnimationHandlerRegistry(); + this.configureAnimationPropertyRegistry(); + this.configureCommands(); + this.configureCompatibility(); + this.configureSkinSplitter(); + this.configureSkinGenerator(); + this.configureUserLimbRegistry(); + this.pivotOverrideRegistry = new PivotOverrideRegistry(); + this.pluginManager.registerEvents(new PlayerListener(), this); + this.pluginManager.registerEvents(new EntityListener(), this); + this.pluginManager.registerEvents(new WorldListener(), this); + this.pluginManager.registerEvents(new InventoryListener(), this); + this.pluginManager.registerEvents(new ChatListener(), this); + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "modelengine:bulk_data"); + if (Bukkit.getPluginManager().getPlugin("MythicMobs") == null) { + this.modelGenerator.importModels(true); + } + } + + public void onDisable() { + if (this.ticker != null) { + this.ticker.stop(); + } + + if (this.modelUpdaters != null) { + this.modelUpdaters.saveAllModels(); + } + } + + private void configureConfig() { + this.configManager = new ConfigManager(this); + this.configCache = new ConfigCache(); + + for (ConfigProperty value : ConfigProperty.values()) { + this.configManager.register(value); + } + + for (ModelState value : ModelState.values()) { + this.configManager.register(value); + } + + this.configManager.save(); + this.configManager.registerReferenceUpdate(AbstractEntityData::updateConfig); + this.configManager.registerReferenceUpdate(AnimationLODHandler::updateConfig); + this.configManager.registerReferenceUpdate(this.configCache::updateConfig); + } + + private void configureKeyframeTypeRegistry() { + this.keyframeTypeRegistry = new KeyframeTypeRegistry(); + this.keyframeTypeRegistry.registerKeyframeType(KeyframeTypes.POSITION); + this.keyframeTypeRegistry.registerKeyframeType(KeyframeTypes.ROTATION); + this.keyframeTypeRegistry.registerKeyframeType(KeyframeTypes.SCALE); + this.keyframeTypeRegistry.registerKeyframeType(KeyframeTypes.SCRIPT); + } + + private void configureScriptReaderRegistry() { + this.scriptReaderRegistry = new ScriptReaderRegistry(); + this.scriptReaderRegistry.registerAndDefault("meg", new ModelEngineScriptReader()); + } + + private void configureBoneBehaviorRegistry() { + this.boneBehaviorRegistry = new BoneBehaviorRegistry(); + BoneBehaviorTypes.HEAD = BoneBehaviorType.Builder.of(HeadImpl::new, null, "head") + .optional("local", Boolean.class) + .optional("inherited", Boolean.class) + .predicate(BoneBehaviorType::noProcedural) + .forced(HeadForcedImpl::new) + .build(); + BoneBehaviorTypes.GHOST = BoneBehaviorType.Builder.of(GhostImpl::new, null, "ghost").renderType(DefaultRenderType.NONE).build(); + BoneBehaviorTypes.MOUNT = BoneBehaviorType.Builder.of(MountImpl::new, MountManagerImpl::new, "mount") + .required("driver", Boolean.class) + .renderType(MountRendererImpl::new) + .build(); + BoneBehaviorTypes.SUB_HITBOX = BoneBehaviorType.Builder.of(SubHitboxImpl::new, null, "sub_hitbox") + .required("dimension", Hitbox.class) + .optional("obb", Boolean.class) + .optional("origin", Vector3f.class) + .optional("rotation", Vector3f.class) + .optional("cube_origin", Vector3f.class) + .renderType(SubHitboxRendererImpl::new) + .ignoreCubes() + .build(); + BoneBehaviorTypes.NAMETAG = BoneBehaviorType.Builder.of(NameTagImpl::new, null, "nametag").renderType(NameTagRendererImpl::new).build(); + BoneBehaviorTypes.ITEM = BoneBehaviorType.Builder.of(HeldItemImpl::new, null, "item") + .required("display", ItemDisplayTransform.class) + .renderType(HeldItemRendererImpl::new) + .build(); + BoneBehaviorTypes.SEGMENT = BoneBehaviorType.Builder.of(SegmentImpl::new, null, "segment") + .required("back_pivot", Boolean.class) + .optional("bounded", Boolean.class) + .optional("min_x", Float.class) + .optional("max_x", Float.class) + .optional("min_y", Float.class) + .optional("max_y", Float.class) + .optional("min_z", Float.class) + .optional("max_z", Float.class) + .optional("extend_rate", Float.class) + .optional("elasticity", Float.class) + .renderType(SegmentRendererImpl::new) + .pivot() + .build(); + BoneBehaviorTypes.TAIL = BoneBehaviorType.Builder.of(TailImpl::new, null, "tail") + .required("back_pivot", Boolean.class) + .optional("bounded", Boolean.class) + .optional("min_x", Float.class) + .optional("max_x", Float.class) + .optional("min_y", Float.class) + .optional("max_y", Float.class) + .optional("min_z", Float.class) + .optional("max_z", Float.class) + .optional("extend_rate", Float.class) + .optional("elasticity", Float.class) + .build(); + BoneBehaviorTypes.LEASH = BoneBehaviorType.Builder.of(LeashImpl::new, LeashManagerImpl::new, "leash") + .optional("main", Boolean.class) + .renderType(LeashRendererImpl::new) + .build(); + BoneBehaviorTypes.PLAYER_LIMB = BoneBehaviorType.Builder.of(PlayerLimbImpl::new, null, "player_limb") + .required("limb", PlayerLimb.Limb.class) + .renderType(DefaultRenderType.NONE) + .ignoreCubes() + .build(); + BoneBehaviorTypes.USER_LIMB = BoneBehaviorType.Builder.of(UserLimbImpl::new, null, "user_limb") + .required("type", String.class) + .renderType(DefaultRenderType.NONE) + .ignoreCubes() + .build(); + this.boneBehaviorRegistry.register(BoneBehaviorTypes.HEAD); + this.boneBehaviorRegistry.register(BoneBehaviorTypes.GHOST); + this.boneBehaviorRegistry.register(BoneBehaviorTypes.MOUNT); + this.boneBehaviorRegistry.register(BoneBehaviorTypes.SUB_HITBOX); + this.boneBehaviorRegistry.register(BoneBehaviorTypes.NAMETAG); + this.boneBehaviorRegistry.register(BoneBehaviorTypes.ITEM); + this.boneBehaviorRegistry.register(BoneBehaviorTypes.SEGMENT); + this.boneBehaviorRegistry.register(BoneBehaviorTypes.TAIL); + this.boneBehaviorRegistry.register(BoneBehaviorTypes.LEASH); + this.boneBehaviorRegistry.register(BoneBehaviorTypes.PLAYER_LIMB); + this.boneBehaviorRegistry.register(BoneBehaviorTypes.USER_LIMB); + } + + private void configureAnimationHandlerRegistry() { + this.animationHandlerRegistry = new AnimationHandlerRegistry(); + this.animationHandlerRegistry.register("priority", PriorityHandler::create); + this.animationHandlerRegistry.register("state_machine", StateMachineHandler::create); + } + + private void configureAnimationPropertyRegistry() { + this.animationPropertyRegistry = new AnimationPropertyRegistry(); + this.animationPropertyRegistry.register("simple", SimpleProperty::create); + } + + private void configureTicker() { + this.ticker = new DualTicker(this, this.getScheduler()); + this.mountPairManager = new MountPairManager(); + this.dataTrackers = new EntityDataTrackers(this, this.getScheduler()); + this.modelUpdaters = new ModelUpdaters(); + this.vfxUpdater = new VFXUpdater(); + this.interactionTracker = new InteractionTracker(); + this.screenManager = new ScreenManager(); + DualTicker.queueRepeatingSyncTask(this.mountPairManager::updatePassengerPosition, 0, 0); + DualTicker.queueRepeatingSyncTask(() -> ServerInfo.CURRENT_TICK++, 0, 0); + DualTicker.queueRepeatingAsyncTask(this.vfxUpdater::updateAllVFXs, 0, 0); + DualTicker.queueRepeatingAsyncTask(this.interactionTracker::raytraceHitboxes, 0, 0); + DualTicker.queueRepeatingSyncTask(this.screenManager::updateAllScreens, 0, 0); + this.ticker.start(); + } + + private void configureMountControllerTypeRegistry() { + this.mountControllerTypeRegistry = new MountControllerTypeRegistry(); + this.mountControllerTypeRegistry.registerAndDefault("walking", MountControllerTypes.WALKING); + this.mountControllerTypeRegistry.register("force_walking", MountControllerTypes.WALKING_FORCE); + this.mountControllerTypeRegistry.register("flying", MountControllerTypes.FLYING); + this.mountControllerTypeRegistry.register("force_flying", MountControllerTypes.FLYING_FORCE); + } + + private void configureNMSHandler() { + String var1 = ServerInfo.NMS_VERSION; + switch (var1) { + case "1.19.4": + this.nmsHandler = new NMSHandler_v1_19_R3(); + break; + case "1.20": + case "1.20.1": + this.nmsHandler = new NMSHandler_v1_20_R1(); + break; + case "1.20.2": + case "1.20.3": + this.nmsHandler = new NMSHandler_v1_20_R2(); + break; + case "1.20.4": + this.nmsHandler = new NMSHandler_v1_20_R3(); + break; + default: + this.nmsHandler = Java21Access.createNMSHandler.call(ServerInfo.NMS_VERSION); + if (this.nmsHandler != null) { + return; + } + + this.nmsHandler = Java25Access.createNMSHandler.call(ServerInfo.NMS_VERSION); + } + + if (this.nmsHandler == null) { + throw new RuntimeException("Unsupported NMS Version: " + ServerInfo.NMS_VERSION); + } + } + + private void configureCommands() { + PluginCommand command = this.getCommand("meg"); + if (command != null) { + command.setExecutor(this.commandRoot = new MECommand(this)); + } + } + + private void configureCompatibility() { + this.compatibilityManager = new CompatibilityManager(this); + this.compatibilityManager.registerSupport("Citizens", () -> this::configureCitizensSupport); + this.compatibilityManager.registerSupport("LibsDisguises", () -> this::configureLibsDisguises); + this.compatibilityManager.registerSupport("ViaVersion", () -> plugin -> { + ServerInfo.HAS_VIAVERSION = true; + return true; + }); + Java21Access.registerCompatibility.call(this.compatibilityManager, this); + } + + private void configureSkinSplitter() { + File internalSkinFolder = TFile.createDirectory(this.getDataFolder(), "internals", "skins"); + SkinSplitterImpl splitter = new SkinSplitterImpl( + TFile.createFile(internalSkinFolder, "steve_mapped.bbmodel"), TFile.createFile(internalSkinFolder, "alex_mapped.bbmodel") + ); + splitter.copyMapped(this); + splitter.reloadMapping(); + this.skinSplitter = splitter; + } + + private void configureSkinGenerator() { + this.skinGenerator = new MineSkinGeneratorService(); + this.configManager.registerReferenceUpdate(this.skinGenerator::onReload); + } + + private void configureUserLimbRegistry() { + this.userLimbRegistry = new UserLimbRegistry(this); + this.userLimbRegistry.generateDefaults(); + } + + private boolean configureCitizensSupport(Plugin plugin) { + ServerInfo.HAS_CITIZENS = true; + CitizensAPI.getTraitFactory().registerTrait(TraitInfo.create(ModelTrait.class)); + this.commandRoot.addSubCommands(new CitizensCommand(this.commandRoot)); + return true; + } + + private boolean configureLibsDisguises(Plugin plugin) { + this.pluginManager.registerEvents(this.disguiseCompatibility = new DisguiseCompatibility(), this); + return true; + } + + @Override + public ModeledEntity createModeledEntityImpl(BaseEntity base, Consumer consumer) { + return new ModeledEntityImpl(base, consumer); + } + + @Override + public ActiveModel createActiveModelImpl( + ModelBlueprint blueprint, Function rendererSupplier, Function handlerSupplier + ) { + return new ActiveModelImpl(blueprint, rendererSupplier, handlerSupplier); + } + + @Override + public VFX createVFXImpl(BaseEntity base, Function rendererSupplier, Consumer consumer) { + return new VFXImpl(base, rendererSupplier, consumer); + } + + @Override + public UUID getDisguiseRelayOrDefault(UUID uuid) { + return this.disguiseCompatibility == null ? uuid : this.disguiseCompatibility.getRelayOrDefault(uuid); + } + + @Override + public AnimationHandler getPriorityHandler(ActiveModel activeModel) { + return new PriorityHandler(activeModel); + } + + @Override + public AnimationHandler getStateMachineHandler(ActiveModel activeModel) { + return new StateMachineHandler(activeModel); + } + + @Override + public int playerProtocolVersion(UUID uuid) { + return ServerInfo.HAS_VIAVERSION ? Via.getAPI().getPlayerVersion(uuid) : getNetworkHandler().getProtocolVersion(); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/animation/handler/PriorityHandler.java b/core/src/main/java/com/ticxo/modelengine/core/animation/handler/PriorityHandler.java new file mode 100644 index 0000000..84b42f5 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/animation/handler/PriorityHandler.java @@ -0,0 +1,409 @@ +package com.ticxo.modelengine.core.animation.handler; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.AnimationPropertyRegistry; +import com.ticxo.modelengine.api.animation.BlueprintAnimation; +import com.ticxo.modelengine.api.animation.ModelState; +import com.ticxo.modelengine.api.animation.Timeline; +import com.ticxo.modelengine.api.animation.handler.AnimationHandler; +import com.ticxo.modelengine.api.animation.handler.IPriorityHandler; +import com.ticxo.modelengine.api.animation.keyframe.KeyframeType; +import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypeRegistry; +import com.ticxo.modelengine.api.animation.keyframe.type.AbstractKeyframe; +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.animation.property.SimpleProperty; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.AnimationEndEvent; +import com.ticxo.modelengine.api.events.AnimationPlayEvent; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import com.ticxo.modelengine.api.utils.state.StateMachine; +import com.ticxo.modelengine.api.utils.state.StateNode; +import java.util.ArrayDeque; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.BiConsumer; +import java.util.function.UnaryOperator; +import org.jetbrains.annotations.Nullable; + +public class PriorityHandler implements IPriorityHandler { + private final ActiveModel activeModel; + private final ModelBlueprint blueprint; + private final Map properties = Maps.newConcurrentMap(); + private final Map updatedProperties = Maps.newConcurrentMap(); + private final Map defaultProperties = Maps.newConcurrentMap(); + private final StateMachine> stateMachine = new StateMachine<>(); + private boolean firstSpawn = true; + + public PriorityHandler(ActiveModel activeModel) { + this.activeModel = activeModel; + this.blueprint = activeModel.getBlueprint(); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.IDLE, 0.25, 0.25, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.WALK, 0.25, 0.25, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.STRAFE, 0.25, 0.25, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP_START, 0.0, 0.25, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP, 0.0, 0.0, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP_END, 0.0, 0.25, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.HOVER, 0.25, 0.25, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.FLY, 0.25, 0.25, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.SPAWN, 0.0, 0.25, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.DEATH, 0.0, 0.0, 1.0)); + this.configureAnimation(); + } + + private void configureAnimation() { + StateNode> spawn = this.stateMachine.createNode(); + StateNode> idle = this.stateMachine.createNode(); + StateNode> walk = this.stateMachine.createNode(); + StateNode> strafe = this.stateMachine.createNode(); + StateNode> jumpStart = this.stateMachine.createNode(); + StateNode> jumpLoop = this.stateMachine.createNode(); + StateNode> jumpEnd = this.stateMachine.createNode(); + StateNode> hover = this.stateMachine.createNode(); + StateNode> fly = this.stateMachine.createNode(); + StateNode> death = this.stateMachine.createNode(); + spawn.setExitAction(baseEntity -> this.playState(ModelState.SPAWN)); + spawn.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + spawn.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + spawn.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + spawn.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart); + spawn.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + spawn.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk); + spawn.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle); + idle.setEntryAction(baseEntity -> this.playState(ModelState.IDLE)); + idle.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + idle.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + idle.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + idle.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart); + idle.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop); + idle.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + idle.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk); + idle.setExitAction(baseEntity -> this.stopState(ModelState.IDLE)); + walk.setEntryAction(baseEntity -> this.playState(ModelState.WALK)); + walk.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + walk.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + walk.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + walk.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart); + walk.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop); + walk.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + walk.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle); + walk.setExitAction(baseEntity -> this.stopState(ModelState.WALK)); + strafe.setEntryAction(baseEntity -> this.playState(ModelState.STRAFE)); + strafe.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + strafe.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + strafe.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + strafe.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart); + strafe.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop); + strafe.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk); + strafe.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle); + strafe.setExitAction(baseEntity -> this.stopState(ModelState.STRAFE)); + jumpStart.setEntryAction(baseEntity -> this.playState(ModelState.JUMP_START)); + jumpStart.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + jumpStart.setCommonPredicate(baseEntity -> this.hasFinishedPlaying(ModelState.JUMP_START)); + jumpStart.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + jumpStart.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_END), jumpEnd); + jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.isWalking(this.activeModel), walk); + jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && !this.isWalking(this.activeModel), idle); + jumpStart.addConnectedNode(baseEntity -> this.hasFinishedPlaying(ModelState.JUMP_START) && this.hasAnimation(ModelState.JUMP), jumpLoop); + jumpLoop.setEntryAction(baseEntity -> this.playState(ModelState.JUMP)); + jumpLoop.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + jumpLoop.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + jumpLoop.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_END), jumpEnd); + jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.isWalking(this.activeModel), walk); + jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && !this.isWalking(this.activeModel), idle); + jumpLoop.setExitAction(baseEntity -> this.stopState(ModelState.JUMP)); + jumpEnd.setEntryAction(baseEntity -> this.playState(ModelState.JUMP_END)); + jumpEnd.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + jumpEnd.setCommonPredicate(baseEntity -> this.hasFinishedPlaying(ModelState.JUMP_END)); + jumpEnd.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + jumpEnd.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + jumpEnd.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart); + jumpEnd.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + jumpEnd.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk); + jumpEnd.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle); + hover.setEntryAction(baseEntity -> this.playState(ModelState.HOVER)); + hover.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + hover.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && this.isWalking(this.activeModel), walk); + hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && !this.isWalking(this.activeModel), idle); + hover.setExitAction(baseEntity -> this.stopState(ModelState.HOVER)); + fly.setEntryAction(baseEntity -> this.playState(ModelState.FLY)); + fly.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + fly.addConnectedNode(baseEntity -> baseEntity.isFlying() && !this.isWalking(this.activeModel) && this.hasAnimation(ModelState.HOVER), hover); + fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && this.isWalking(this.activeModel), walk); + fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && !this.isWalking(this.activeModel), idle); + fly.setExitAction(baseEntity -> this.stopState(ModelState.FLY)); + death.setEntryAction(baseEntity -> { + this.forceStopAllAnimations(); + this.playState(ModelState.DEATH); + }); + this.stateMachine.setEntryNode(spawn); + } + + private boolean hasAnimation(ModelState state) { + return this.blueprint.getAnimations().containsKey(state.getString()); + } + + private boolean hasFinishedPlaying(ModelState state) { + IAnimationProperty animation = this.getAnimation(state.getString()); + return animation == null || animation.getPhase() == IAnimationProperty.Phase.LERPOUT; + } + + private void stopState(ModelState state) { + AnimationHandler.DefaultProperty defProperty = this.getDefaultProperty(state); + this.stopAnimation(defProperty.getAnimation()); + } + + @Override + public void prepare() { + this.stateMachine.execute(this.activeModel.getModeledEntity().getBase()); + this.firstSpawn = false; + this.updatedProperties.clear(); + this.updatedProperties.putAll(this.properties); + + for (String name : List.copyOf(this.properties.keySet())) { + IAnimationProperty property = this.updatedProperties.get(name); + if (property != null && !property.update()) { + this.updatedProperties.remove(name); + this.forceStopAnimation(name); + } + } + } + + @Override + public void updateBone(ModelBone bone) { + this.updateBone(bone, null); + } + + @Override + public void updateBone(ModelBone bone, @Nullable UnaryOperator propertyMapper) { + bone.setHasGlobalRotation(false); + KeyframeTypeRegistry registry = ModelEngineAPI.getAPI().getKeyframeTypeRegistry(); + ArrayDeque stack = new ArrayDeque<>(); + + for (String typeName : registry.getKeys()) { + KeyframeType, ?> type = (KeyframeType, ?>)registry.get(typeName); + if (!type.isGlobal()) { + this.fillUpdateStack(stack, type, bone); + + while (!stack.isEmpty()) { + IAnimationProperty property = stack.pop(); + Timeline timeline = property.getBlueprintAnimation().getTimelines().get(property.getBlueprintBone(bone).getUuid()); + if (timeline != null && timeline.isGlobalRotation()) { + bone.setHasGlobalRotation(true); + } + + type.updateBone(IPriorityHandler.class, this, bone, propertyMapper == null ? property : propertyMapper.apply(property)); + } + } + } + } + + @Override + public boolean hasFinishedAllAnimations() { + for (IAnimationProperty property : this.properties.values()) { + if (!property.isFinished()) { + return false; + } + } + + return true; + } + + @Override + public void setDefaultProperty(AnimationHandler.DefaultProperty defaultProperty) { + this.defaultProperties.put(defaultProperty.getState(), defaultProperty); + } + + @Override + public AnimationHandler.DefaultProperty getDefaultProperty(ModelState state) { + return this.defaultProperties.get(state); + } + + private void fillUpdateStack(ArrayDeque stack, KeyframeType type, ModelBone bone) { + UUID boneUuid = bone.getBlueprintBone().getUuid(); + + for (IAnimationProperty property : this.updatedProperties.values()) { + if (property.getBlueprintAnimation().getModelBlueprint() != this.blueprint) { + stack.push(property); + if (property.isOverride() + && property.containsKeyframe(type, property.getBlueprintBone(bone).getUuid()) + && property.getPhase() == IAnimationProperty.Phase.PLAY) { + return; + } + } + } + + for (String name : this.blueprint.getAnimationDescendingPriority()) { + IAnimationProperty propertyx = this.updatedProperties.get(name); + if (propertyx != null) { + stack.push(propertyx); + if (propertyx.isOverride() && propertyx.containsKeyframe(type, boneUuid) && propertyx.getPhase() == IAnimationProperty.Phase.PLAY) { + break; + } + } + } + } + + @Override + public void tickGlobal() { + KeyframeTypeRegistry registry = ModelEngineAPI.getAPI().getKeyframeTypeRegistry(); + + for (IAnimationProperty property : this.properties.values()) { + for (String typeName : registry.getKeys()) { + KeyframeType, ?> type = (KeyframeType, ?>)registry.get(typeName); + if (type.isGlobal()) { + type.updateModel(IPriorityHandler.class, this, property); + } + } + } + } + + @Override + public void forEachProperty(BiConsumer consumer) { + this.properties.forEach(consumer); + } + + @Nullable + @Override + public IAnimationProperty getAnimation(String animation) { + return this.properties.get(animation); + } + + @Override + public Map getAnimations() { + return ImmutableMap.copyOf(this.properties); + } + + @Nullable + @Override + public IAnimationProperty playAnimation(String animation, double lerpIn, double lerpOut, double speed, boolean force) { + BlueprintAnimation blueprintAnimation = this.blueprint.getAnimations().get(animation); + if (blueprintAnimation == null) { + return null; + } else { + SimpleProperty property = new SimpleProperty(this.activeModel, blueprintAnimation, lerpIn, lerpOut, speed); + return this.playAnimation(property, force) ? property : null; + } + } + + @Override + public boolean playAnimation(IAnimationProperty property, boolean force) { + AnimationPlayEvent event = new AnimationPlayEvent(this.activeModel, property); + ModelEngineAPI.callEvent(event); + if (event.isCancelled()) { + return false; + } else { + String name = property.getName(); + if (!this.properties.containsKey(name)) { + this.properties.put(name, property); + return true; + } else { + IAnimationProperty old = this.properties.get(name); + if (!force && !old.canReplace()) { + return false; + } else { + this.properties.put(name, property); + return true; + } + } + } + } + + @Override + public void playState(ModelState state) { + AnimationHandler.DefaultProperty defProperty = this.getDefaultProperty(state); + IAnimationProperty property = this.firstSpawn + ? defProperty.build(this.activeModel, 0.0, defProperty.getLerpOut(), defProperty.getSpeed()) + : defProperty.build(this.activeModel); + if (property != null) { + property.setForceLoopMode(state.getLoopMode()); + property.setForceOverride(state.getOverride()); + this.playAnimation(property, false); + } + } + + @Override + public boolean isPlayingAnimation(String animation) { + return this.properties.containsKey(animation); + } + + @Override + public void stopAnimation(String animation) { + IAnimationProperty property = this.properties.get(animation); + if (property != null) { + if (property.getLerpOut() > 1.0E-5F) { + property.stop(); + } else { + this.forceStopAnimation(animation); + } + } + } + + @Override + public void forceStopAnimation(String animation) { + IAnimationProperty property = this.properties.remove(animation); + if (property != null) { + AnimationEndEvent event = new AnimationEndEvent(this.activeModel, property); + ModelEngineAPI.callEvent(event); + if (property instanceof SimpleProperty simpleProperty && simpleProperty.getOnEndTask() != null) { + simpleProperty.getOnEndTask().run(); + } + } + } + + @Override + public void forceStopAllAnimations() { + for (IAnimationProperty property : this.properties.values()) { + AnimationEndEvent event = new AnimationEndEvent(this.activeModel, property); + ModelEngineAPI.callEvent(event); + if (property instanceof SimpleProperty simpleProperty && simpleProperty.getOnEndTask() != null) { + simpleProperty.getOnEndTask().run(); + } + } + + this.properties.clear(); + } + + @Override + public void save(SavedData data) { + IPriorityHandler.super.save(data); + SavedData animationData = new SavedData(); + this.getAnimations().forEach((key, property) -> property.save().ifPresent(propertyData -> animationData.putData(key, propertyData))); + data.putData("animations", animationData); + } + + @Override + public void load(SavedData data) { + IPriorityHandler.super.load(data); + AnimationPropertyRegistry registry = ModelEngineAPI.getAnimationPropertyRegistry(); + data.getData("animations").ifPresent(animationData -> { + for (String key : animationData.keySet()) { + animationData.getData(key).ifPresent(propertyData -> { + IAnimationProperty property = registry.createAnimationProperty(this, propertyData); + this.playAnimation(property, true); + }); + } + }); + } + + public static PriorityHandler create(ActiveModel model, SavedData data) { + PriorityHandler handler = new PriorityHandler(model); + handler.load(data); + return handler; + } + + @Override + public ActiveModel getActiveModel() { + return this.activeModel; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/animation/handler/StateMachineHandler.java b/core/src/main/java/com/ticxo/modelengine/core/animation/handler/StateMachineHandler.java new file mode 100644 index 0000000..14f8e46 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/animation/handler/StateMachineHandler.java @@ -0,0 +1,720 @@ +package com.ticxo.modelengine.core.animation.handler; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.AnimationPropertyRegistry; +import com.ticxo.modelengine.api.animation.BlueprintAnimation; +import com.ticxo.modelengine.api.animation.ModelState; +import com.ticxo.modelengine.api.animation.Timeline; +import com.ticxo.modelengine.api.animation.handler.AnimationHandler; +import com.ticxo.modelengine.api.animation.handler.IStateMachineHandler; +import com.ticxo.modelengine.api.animation.keyframe.KeyframeType; +import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypeRegistry; +import com.ticxo.modelengine.api.animation.keyframe.type.AbstractKeyframe; +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.animation.property.SimpleProperty; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.AnimationEndEvent; +import com.ticxo.modelengine.api.events.AnimationPlayEvent; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.io.DataIO; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.state.StateMachine; +import com.ticxo.modelengine.api.utils.state.StateNode; +import java.util.ArrayDeque; +import java.util.HashMap; +import java.util.Map; +import java.util.Queue; +import java.util.TreeMap; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import org.jetbrains.annotations.Nullable; + +public class StateMachineHandler implements IStateMachineHandler { + private static int DEFAULT_PRIORITY; + private final ActiveModel activeModel; + private final ModelBlueprint blueprint; + private final Map defaultProperties = Maps.newConcurrentMap(); + private final TreeMap stateMachines = new TreeMap<>(); + private final Queue actionQueue = new ConcurrentLinkedQueue<>(); + private boolean firstSpawn = true; + + public StateMachineHandler(ActiveModel activeModel) { + this.activeModel = activeModel; + this.blueprint = activeModel.getBlueprint(); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.IDLE, 0.25, 0.0, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.WALK, 0.25, 0.0, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.STRAFE, 0.25, 0.0, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP_START, 0.0, 0.0, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP, 0.0, 0.0, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.JUMP_END, 0.0, 0.0, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.HOVER, 0.25, 0.0, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.FLY, 0.25, 0.0, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.SPAWN, 0.0, 0.0, 1.0)); + this.setDefaultProperty(new AnimationHandler.DefaultProperty(ModelState.DEATH, 0.0, 0.0, 1.0)); + this.configureAnimation(); + } + + private void configureAnimation() { + StateMachineHandler.AnimationStateMachine stateMachine = new StateMachineHandler.AnimationStateMachine(false); + StateNode> root = stateMachine.getRootNode(); + StateNode> spawn = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.SPAWN)); + StateNode> idle = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.IDLE)); + StateNode> walk = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.WALK)); + StateNode> strafe = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.STRAFE)); + StateNode> jumpStart = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.JUMP_START)); + StateNode> jumpLoop = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.JUMP)); + StateNode> jumpEnd = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.JUMP_END)); + StateNode> hover = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.HOVER)); + StateNode> fly = stateMachine.createAnimationNode(() -> this.createStateProperty(ModelState.FLY)); + StateNode> death = stateMachine.createAnimationNode(() -> { + this.forceStopAllAnimations(); + return this.createStateProperty(ModelState.DEATH); + }); + root.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + root.addConnectedNode(baseEntity -> this.hasAnimation(ModelState.SPAWN), spawn); + root.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + root.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + root.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart); + root.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop); + root.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + root.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk); + root.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle); + spawn.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + spawn.setCommonPredicate(baseEntity -> stateMachine.hasFinishedPlaying(ModelState.SPAWN)); + spawn.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + spawn.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + spawn.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart); + spawn.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop); + spawn.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + spawn.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk); + spawn.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle); + idle.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + idle.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + idle.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + idle.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart); + idle.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop); + idle.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + idle.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk); + walk.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + walk.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + walk.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + walk.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart); + walk.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop); + walk.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + walk.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle); + strafe.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + strafe.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + strafe.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + strafe.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart); + strafe.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP), jumpLoop); + strafe.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk); + strafe.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle); + jumpStart.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + jumpStart.setCommonPredicate(baseEntity -> stateMachine.hasFinishedPlaying(ModelState.JUMP_START)); + jumpStart.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + jumpStart.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_END), jumpEnd); + jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.isWalking(this.activeModel), walk); + jumpStart.addConnectedNode(baseEntity -> !baseEntity.isJumping() && !this.isWalking(this.activeModel), idle); + jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + jumpLoop.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + jumpLoop.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_END), jumpEnd); + jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && this.isWalking(this.activeModel), walk); + jumpLoop.addConnectedNode(baseEntity -> !baseEntity.isJumping() && !this.isWalking(this.activeModel), idle); + jumpEnd.addForceConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + jumpEnd.setCommonPredicate(baseEntity -> stateMachine.hasFinishedPlaying(ModelState.JUMP_END)); + jumpEnd.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + jumpEnd.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.hasAnimation(ModelState.HOVER), hover); + jumpEnd.addConnectedNode(baseEntity -> baseEntity.isJumping() && this.hasAnimation(ModelState.JUMP_START), jumpStart); + jumpEnd.addConnectedNode(baseEntity -> baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + jumpEnd.addConnectedNode(baseEntity -> this.isWalking(this.activeModel), walk); + jumpEnd.addConnectedNode(baseEntity -> !this.isWalking(this.activeModel), idle); + hover.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + hover.addConnectedNode(baseEntity -> baseEntity.isFlying() && this.isWalking(this.activeModel) && this.hasAnimation(ModelState.FLY), fly); + hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && this.isWalking(this.activeModel), walk); + hover.addConnectedNode(baseEntity -> !baseEntity.isFlying() && !this.isWalking(this.activeModel), idle); + fly.addConnectedNode(baseEntity -> !baseEntity.isAlive(), death); + fly.addConnectedNode(baseEntity -> baseEntity.isFlying() && !this.isWalking(this.activeModel) && this.hasAnimation(ModelState.HOVER), hover); + fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && baseEntity.isStrafing() && this.hasAnimation(ModelState.STRAFE), strafe); + fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && this.isWalking(this.activeModel), walk); + fly.addConnectedNode(baseEntity -> !baseEntity.isFlying() && !this.isWalking(this.activeModel), idle); + this.stateMachines.put(DEFAULT_PRIORITY, stateMachine); + } + + @Override + public void prepare() { + while (!this.actionQueue.isEmpty()) { + this.actionQueue.poll().run(); + } + + synchronized (this.stateMachines) { + this.stateMachines.values().forEach(machine -> { + machine.materializeQueued(); + machine.execute(this.activeModel.getModeledEntity().getBase()); + machine.queuedAnimation = null; + }); + } + + this.firstSpawn = false; + } + + @Override + public void updateBone(ModelBone bone) { + this.updateBone(bone, null); + } + + @Override + public void updateBone(ModelBone bone, @Nullable UnaryOperator propertyMapper) { + bone.setHasGlobalRotation(false); + KeyframeTypeRegistry registry = ModelEngineAPI.getAPI().getKeyframeTypeRegistry(); + ArrayDeque stack = new ArrayDeque<>(); + + for (String typeName : registry.getKeys()) { + KeyframeType, ?> type = (KeyframeType, ?>)registry.get(typeName); + if (!type.isGlobal()) { + this.fillUpdateStack(stack, type, bone); + + while (!stack.isEmpty()) { + StateMachineHandler.AnimationStateMachine stateMachine = stack.pop(); + IAnimationProperty currentProperty = stateMachine.currentAnimation; + IAnimationProperty lastProperty = stateMachine.lastAnimation; + bone.setHasGlobalRotation(this.isGlobalRotation(currentProperty, bone) || this.isGlobalRotation(lastProperty, bone)); + if (propertyMapper != null) { + currentProperty = propertyMapper.apply(currentProperty); + lastProperty = propertyMapper.apply(lastProperty); + } + + type.updateBone(IStateMachineHandler.class, this, bone, currentProperty, lastProperty); + } + } + } + } + + private boolean isGlobalRotation(IAnimationProperty property, ModelBone bone) { + if (property == null) { + return false; + } else { + BlueprintAnimation animation = property.getBlueprintAnimation(); + if (animation == null) { + return false; + } else { + Map timelines = animation.getTimelines(); + if (timelines == null) { + return false; + } else { + Timeline timeline = timelines.get(bone.getBlueprintBone().getUuid()); + return timeline == null ? false : timeline.isGlobalRotation(); + } + } + } + } + + @Override + public boolean hasFinishedAllAnimations() { + synchronized (this.stateMachines) { + for (StateMachineHandler.AnimationStateMachine machine : this.stateMachines.values()) { + if (machine.currentAnimation != null && !machine.currentAnimation.isFinished() && !machine.currentAnimation.isIgnoreDeath()) { + return false; + } + } + + return true; + } + } + + @Override + public void setDefaultProperty(AnimationHandler.DefaultProperty defaultProperty) { + this.defaultProperties.put(defaultProperty.getState(), defaultProperty); + } + + @Override + public AnimationHandler.DefaultProperty getDefaultProperty(ModelState state) { + return this.defaultProperties.get(state); + } + + @Override + public void tickGlobal() { + synchronized (this.stateMachines) { + for (StateMachineHandler.AnimationStateMachine machine : this.stateMachines.values()) { + if (machine.currentAnimation != null) { + KeyframeTypeRegistry registry = ModelEngineAPI.getAPI().getKeyframeTypeRegistry(); + + for (String typeName : registry.getKeys()) { + KeyframeType, ?> type = (KeyframeType, ?>)registry.get(typeName); + if (type.isGlobal()) { + type.updateModel(IStateMachineHandler.class, this, machine.currentAnimation, machine.lastAnimation); + } + } + } + } + } + } + + @Nullable + @Override + public IAnimationProperty playAnimation(String animation, double lerpIn, double lerpOut, double speed, boolean force) { + return this.playAnimation(1, animation, lerpIn, lerpOut, speed, force); + } + + @Override + public boolean playAnimation(IAnimationProperty property, boolean force) { + return this.playAnimation(1, property, force); + } + + private void fillUpdateStack(ArrayDeque stack, KeyframeType type, ModelBone bone) { + if (!this.stateMachines.isEmpty()) { + UUID boneUuid = bone.getBlueprintBone().getUuid(); + + for (Entry entry = this.stateMachines.lastEntry(); + entry != null; + entry = this.stateMachines.lowerEntry(entry.getKey()) + ) { + StateMachineHandler.AnimationStateMachine machine = entry.getValue(); + IAnimationProperty currentProperty = machine.currentAnimation; + IAnimationProperty lastProperty = machine.lastAnimation; + if (currentProperty != null) { + stack.push(machine); + if (this.isLastProperty(currentProperty, type, boneUuid) && (lastProperty == null || this.isLastProperty(lastProperty, type, boneUuid))) { + break; + } + } + } + } + } + + private boolean isLastProperty(IAnimationProperty property, KeyframeType type, UUID boneUuid) { + return property.isOverride() && property.containsKeyframe(type, boneUuid) && property.getPhase() == IAnimationProperty.Phase.PLAY; + } + + @Nullable + @Override + public IAnimationProperty getAnimation(String animation) { + synchronized (this.stateMachines) { + for (StateMachineHandler.AnimationStateMachine machine : this.stateMachines.values()) { + if (machine.isQueued(this.blueprint, animation)) { + return machine.queuedAnimation; + } + + if (machine.isPlaying(animation)) { + return machine.currentAnimation; + } + } + + return null; + } + } + + @Override + public Map getAnimations() { + HashMap map = new HashMap<>(); + + for (Entry entry : this.stateMachines.entrySet()) { + int id = entry.getKey(); + StateMachineHandler.AnimationStateMachine stateMachine = entry.getValue(); + IAnimationProperty animation = stateMachine.getEffectiveAnimation(); + if (animation != null) { + map.put(id + ":" + animation.getName(), animation); + } + } + + return map; + } + + @Nullable + @Override + public IAnimationProperty getAnimation(int priority, ModelBlueprint source, String animation) { + StateMachineHandler.AnimationStateMachine machine = this.stateMachines.get(priority); + if (machine == null) { + return null; + } else if (machine.isQueued(source, animation)) { + return machine.queuedAnimation; + } else { + return machine.isPlaying(source, animation) ? machine.currentAnimation : null; + } + } + + @Nullable + @Override + public IAnimationProperty playAnimation(int priority, ModelBlueprint source, String animation, double lerpIn, double lerpOut, double speed, boolean force) { + BlueprintAnimation blueprintAnimation = source.getAnimations().get(animation); + if (blueprintAnimation == null) { + return null; + } else { + SimpleProperty property = new SimpleProperty(this.activeModel, blueprintAnimation, lerpIn, lerpOut, speed); + return this.playAnimation(priority, property, force) ? property : null; + } + } + + @Override + public boolean playAnimation(int priority, IAnimationProperty property, boolean force) { + AnimationPlayEvent event = new AnimationPlayEvent(this.activeModel, property); + ModelEngineAPI.callEvent(event); + if (event.isCancelled()) { + return false; + } else { + synchronized (this.stateMachines) { + StateMachineHandler.AnimationStateMachine machine = this.stateMachines + .computeIfAbsent(priority, id -> new StateMachineHandler.AnimationStateMachine(true)); + if (force || machine.queuedAnimation == null && !machine.isPlaying(property.getName())) { + machine.queuedAnimation = property; + machine.queuedForce = force; + return true; + } else { + return false; + } + } + } + } + + @Override + public void refreshState(AnimationHandler.DefaultProperty property) { + StateMachineHandler.AnimationStateMachine machine = this.stateMachines.get(DEFAULT_PRIORITY); + if (machine != null && machine.isPlaying(property.getAnimation())) { + machine.forceReentry(this.activeModel.getModeledEntity().getBase()); + } + } + + @Override + public boolean isPlayingAnimation(String animation) { + return this.getAnimation(animation) != null; + } + + @Override + public boolean isPlayingAnimation(int priority, ModelBlueprint source, String animation) { + return this.getAnimation(priority, source, animation) != null; + } + + @Override + public void stopAnimation(String animation) { + this.stateMachines.keySet().forEach(integer -> this.stopAnimation(integer, animation)); + } + + @Override + public void stopAnimation(int priority, ModelBlueprint source, String animation) { + StateMachineHandler.AnimationStateMachine machine = this.stateMachines.get(priority); + if (machine != null) { + if (machine.isQueued(source, animation)) { + machine.queuedAnimation = null; + } else { + if (machine.isPlaying(source, animation)) { + if (machine.currentAnimation.getLerpOut() > 1.0E-5F) { + machine.currentAnimation.stop(); + } else { + machine.getCurrentNode().addForceConnectedNode(baseEntity -> true, machine.getRootNode()); + } + } + } + } + } + + @Override + public void forceStopAnimation(String animation) { + this.stateMachines.keySet().forEach(integer -> this.forceStopAnimation(integer, animation)); + } + + @Override + public void forceStopAnimation(int priority, ModelBlueprint source, String animation) { + StateMachineHandler.AnimationStateMachine machine = this.stateMachines.get(priority); + if (machine != null) { + if (machine.isQueued(source, animation)) { + machine.queuedAnimation = null; + } else { + if (machine.isPlaying(source, animation)) { + machine.getCurrentNode().addForceConnectedNode(baseEntity -> true, machine.getRootNode()); + } + } + } + } + + @Override + public void forceStopAllAnimations() { + this.actionQueue.add(() -> this.stateMachines.keySet().removeIf(key -> { + if (key == DEFAULT_PRIORITY) { + return false; + } else { + StateMachineHandler.AnimationStateMachine machine = this.stateMachines.get(key); + return machine.getCurrentAnimation() == null || !machine.getCurrentAnimation().isIgnoreDeath(); + } + })); + } + + private boolean hasAnimation(ModelState state) { + return this.blueprint.getAnimations().containsKey(state.getString()); + } + + @Nullable + private IAnimationProperty createStateProperty(ModelState state) { + AnimationHandler.DefaultProperty defProperty = this.getDefaultProperty(state); + IAnimationProperty property = this.firstSpawn + ? defProperty.buildRef(this.activeModel, 0.0, defProperty.getLerpOut(), defProperty.getSpeed()) + : defProperty.buildRef(this.activeModel); + if (property != null) { + property.setForceLoopMode(state.getLoopMode()); + property.setForceOverride(state.getOverride()); + } + + return property; + } + + @Override + public void save(SavedData data) { + IStateMachineHandler.super.save(data); + SavedData stateMachinesData = new SavedData(); + this.stateMachines.forEach((id, asm) -> asm.save().ifPresent(smd -> stateMachinesData.putData(Integer.toString(id), smd))); + data.putData("state_machines", stateMachinesData); + } + + @Override + public void load(SavedData data) { + IStateMachineHandler.super.load(data); + data.getData("state_machines").ifPresent(stateMachinesData -> { + for (String key : stateMachinesData.keySet()) { + int id = Integer.parseInt(key); + stateMachinesData.getData(key).ifPresent(smd -> { + StateMachineHandler.AnimationStateMachine asm = new StateMachineHandler.AnimationStateMachine(true); + asm.load(smd); + this.stateMachines.put(id, asm); + }); + } + }); + } + + public static StateMachineHandler create(ActiveModel model, SavedData data) { + StateMachineHandler handler = new StateMachineHandler(model); + handler.load(data); + return handler; + } + + @Override + public ActiveModel getActiveModel() { + return this.activeModel; + } + + @Override + public ModelBlueprint getBlueprint() { + return this.blueprint; + } + + public TreeMap getStateMachines() { + return this.stateMachines; + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> DEFAULT_PRIORITY = ConfigProperty.DEFAULT_PRIORITY.getInt()); + } + + public class AnimationStateMachine extends StateMachine> implements DataIO { + protected final boolean saved; + protected StateNode> rootNode; + @Nullable + protected IAnimationProperty lastAnimation; + @Nullable + protected IAnimationProperty currentAnimation; + @Nullable + protected IAnimationProperty queuedAnimation; + protected boolean queuedForce; + + @Override + public StateNode> getCurrentNode() { + return this.currentNode == null ? this.getRootNode() : this.currentNode; + } + + public StateNode> getRootNode() { + if (this.rootNode == null) { + this.rootNode = new StateNode<>(this); + this.rootNode.setEntryAction(baseEntity -> this.currentAnimation = null); + this.rootNode.setExitAction(baseEntity -> { + this.rootNode.clearForceConnectedNodes(); + this.rootNode.clearConnectedNodes(); + this.lastAnimation = this.currentAnimation; + }); + this.setEntryNode(this.rootNode); + } + + return this.rootNode; + } + + public StateNode> createAnimationNode(Supplier propertySupplier) { + StateNode> node = new StateNode<>(this); + node.setEntryAction(baseEntity -> this.currentAnimation = propertySupplier.get()); + node.setAction(baseEntity -> { + if (this.currentAnimation != null) { + this.currentAnimation.update(); + } + + if (this.lastAnimation != null && this.lastAnimation != this.currentAnimation) { + this.lastAnimation.update(); + } + }); + node.setExitAction(baseEntity -> { + AnimationEndEvent event = new AnimationEndEvent(StateMachineHandler.this.activeModel, this.currentAnimation); + ModelEngineAPI.callEvent(event); + if (this.currentAnimation instanceof SimpleProperty simpleProperty && simpleProperty.getOnEndTask() != null) { + simpleProperty.getOnEndTask().run(); + } + + this.lastAnimation = this.currentAnimation; + }); + return node; + } + + private void materializeQueued() { + if (this.queuedAnimation != null) { + IAnimationProperty property = this.queuedAnimation; + StateNode> currentNode = this.getCurrentNode(); + StateNode> node = this.createAnimationNode(() -> property); + if (this.queuedForce) { + currentNode.clearConnectedNodes(); + currentNode.clearForceConnectedNodes(); + } + + node.addConnectedNode(baseEntity -> property.isEnded(), this.getRootNode()); + currentNode.addForceConnectedNode(baseEntity -> true, node); + } + } + + public boolean hasFinishedPlaying(ModelState modelState) { + return !this.isPlaying(StateMachineHandler.this.getDefaultProperty(modelState).getAnimation()); + } + + public boolean isPlaying(String animation) { + return this.isPlaying(StateMachineHandler.this.blueprint, animation); + } + + public boolean isPlaying(ModelBlueprint source, String animation) { + if (this.currentAnimation != null + && this.currentAnimation.getBlueprintAnimation().getModelBlueprint() == source + && this.currentAnimation.getBlueprintAnimation().getName().equals(animation) + && this.currentAnimation.getPhase() != IAnimationProperty.Phase.LERPOUT) { + switch (this.currentAnimation.getLoopMode()) { + case ONCE: + if (this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength()) { + return true; + } + break; + case LOOP: + if (this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength() + 0.05) { + return true; + } + break; + default: + return true; + } + } + + return false; + } + + public boolean isQueued(ModelBlueprint source, String animation) { + return this.queuedAnimation != null + && this.queuedAnimation.getBlueprintAnimation().getModelBlueprint() == source + && this.queuedAnimation.getBlueprintAnimation().getName().equals(animation); + } + + @Nullable + public IAnimationProperty getEffectiveAnimation() { + return this.queuedAnimation != null ? this.queuedAnimation : this.currentAnimation; + } + + public boolean isPlayingWithLog(ModelBlueprint source, String animation) { + if (this.currentAnimation == null) { + TLogger.log("Current Animation is null"); + return false; + } else if (this.currentAnimation.getBlueprintAnimation().getModelBlueprint() != source) { + TLogger.log("Current Animation is not from source"); + return false; + } else if (!this.currentAnimation.getBlueprintAnimation().getName().equals(animation)) { + TLogger.log("Current Animation name is not equal to animation"); + return false; + } else if (this.currentAnimation.getPhase() == IAnimationProperty.Phase.LERPOUT) { + TLogger.log("Current Animation is in LERPOUT phase"); + return false; + } else { + return switch (this.currentAnimation.getLoopMode()) { + case ONCE -> { + TLogger.log("Once: " + (this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength())); + yield this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength(); + } + case LOOP -> { + TLogger.log("Loop: " + (this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength() + 0.05)); + yield this.currentAnimation.getTime() < this.currentAnimation.getBlueprintAnimation().getLength() + 0.05; + } + default -> true; + }; + } + } + + public boolean isPlayingOrEnding(String animation) { + return this.isPlayingOrEnding(StateMachineHandler.this.blueprint, animation); + } + + public boolean isPlayingOrEnding(ModelBlueprint source, String animation) { + return this.currentAnimation != null + && this.currentAnimation.getBlueprintAnimation().getModelBlueprint() == source + && this.currentAnimation.getName().equals(animation) + && !this.currentAnimation.isEnded(); + } + + public void forceReentry(BaseEntity base) { + this.getCurrentNode().acceptEntry(base); + } + + @Override + public void save(SavedData data) { + if (this.saved) { + if (this.lastAnimation != null) { + this.lastAnimation.save().ifPresent(data1 -> data.putData("last_animation", data1)); + } + + if (this.currentAnimation != null) { + this.currentAnimation.save().ifPresent(data1 -> data.putData("current_animation", data1)); + } + } + } + + @Override + public void load(SavedData data) { + AnimationPropertyRegistry registry = ModelEngineAPI.getAnimationPropertyRegistry(); + data.getData("last_animation").ifPresent(property -> this.lastAnimation = registry.createAnimationProperty(StateMachineHandler.this, property)); + data.getData("current_animation").ifPresent(property -> this.currentAnimation = registry.createAnimationProperty(StateMachineHandler.this, property)); + StateNode> currentNode = this.getCurrentNode(); + if (this.currentAnimation != null) { + StateNode> node = this.createAnimationNode(() -> this.currentAnimation); + node.addConnectedNode(baseEntity -> this.currentAnimation.isEnded(), this.getRootNode()); + currentNode.addForceConnectedNode(baseEntity -> true, node); + } + } + + public AnimationStateMachine(boolean saved) { + this.saved = saved; + } + + @Nullable + public IAnimationProperty getLastAnimation() { + return this.lastAnimation; + } + + public void setLastAnimation(@Nullable IAnimationProperty lastAnimation) { + this.lastAnimation = lastAnimation; + } + + @Nullable + public IAnimationProperty getCurrentAnimation() { + return this.currentAnimation; + } + + public void setCurrentAnimation(@Nullable IAnimationProperty currentAnimation) { + this.currentAnimation = currentAnimation; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/animation/script/ModelEngineScriptReader.java b/core/src/main/java/com/ticxo/modelengine/core/animation/script/ModelEngineScriptReader.java new file mode 100644 index 0000000..5e0632d --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/animation/script/ModelEngineScriptReader.java @@ -0,0 +1,222 @@ +package com.ticxo.modelengine.core.animation.script; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.animation.script.ScriptReader; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.NameTag; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.registry.TUnaryRegistry; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import org.bukkit.Color; + +public class ModelEngineScriptReader extends TUnaryRegistry>> implements ScriptReader { + private boolean shouldPrintWarning; + + public ModelEngineScriptReader() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + this.register("changeparent", this::changeParent); + this.register("partvis", this::partVisibility); + this.register("tint", this::tint); + this.register("enchant", this::enchant); + this.register("tag", this::tag); + this.register("changepart", this::changePart); + this.register("remap", this::remap); + } + + public void updateConfig() { + this.shouldPrintWarning = ConfigProperty.SCRIPT_WARNING.getBoolean(); + } + + @Override + public void read(IAnimationProperty property, String script) { + String[] scriptSplit = script.split("\\{", 2); + String name = scriptSplit[0].toLowerCase(Locale.ENGLISH); + BiConsumer> function = this.get(name); + if (function == null) { + if (this.shouldPrintWarning) { + TLogger.warn("Unknown Model Engine script: " + script); + } + } else if (scriptSplit.length != 2) { + if (this.shouldPrintWarning) { + TLogger.warn("Invalid Model Engine script: " + script); + } + } else { + ActiveModel model = property.getModel(); + ModelBlueprint blueprint = model.getBlueprint(); + HashMap map = new HashMap<>(); + String[] parameters = scriptSplit[1].substring(0, scriptSplit[1].length() - 1).split(";"); + + for (String param : parameters) { + String[] entry = param.split("=", 2); + map.put(entry[0].strip().toLowerCase(Locale.ENGLISH), entry.length == 2 ? this.getAnimationPlaceholder(blueprint, entry[1].strip()) : ""); + } + + function.accept(model, map); + } + } + + private String getAnimationPlaceholder(ModelBlueprint blueprint, String placeholder) { + if (placeholder.startsWith("<") && placeholder.endsWith(">")) { + String key = placeholder.substring(1, placeholder.length() - 1); + return blueprint.getAnimationsPlaceholders().getOrDefault(key, placeholder); + } else { + return placeholder; + } + } + + private void changeParent(ActiveModel model, Map param) { + String parentPart = param.get("parent"); + String childPart = param.get("child"); + model.getBone(parentPart).ifPresent(parent -> model.getBone(childPart).ifPresent(child -> child.setParent(parent))); + } + + private void partVisibility(ActiveModel model, Map param) { + String part = param.get("part"); + boolean visible = Boolean.parseBoolean(param.get("visible")); + boolean exact = Boolean.parseBoolean(param.get("exact")); + if (exact) { + model.getBone(part).ifPresent(bonex -> bonex.setVisible(visible)); + } else { + for (Entry bone : model.getBones().entrySet()) { + if (bone.getKey().contains(part)) { + bone.getValue().setVisible(visible); + } + } + } + } + + private void tint(ActiveModel model, Map param) { + String part = param.get("part"); + String colorString = param.get("color"); + if (colorString.startsWith("#")) { + colorString = colorString.substring(1); + } + + Color color = Color.fromRGB(Integer.parseInt(colorString, 16)); + boolean exact = Boolean.parseBoolean(param.get("exact")); + boolean damage = Boolean.parseBoolean(param.get("damage")); + if (part.isBlank()) { + if (damage) { + model.setDamageTint(color); + } else { + model.setDefaultTint(color); + } + } else if (exact) { + model.getBone(part).ifPresent(bone -> { + if (damage) { + bone.setDamageTint(color); + } else { + bone.setDefaultTint(color); + } + }); + } else { + for (Entry entry : model.getBones().entrySet()) { + if (entry.getKey().contains(part)) { + if (damage) { + entry.getValue().setDamageTint(color); + } else { + entry.getValue().setDefaultTint(color); + } + } + } + } + } + + private void enchant(ActiveModel model, Map param) { + String part = param.get("part"); + boolean enchant = Boolean.parseBoolean(param.get("enchant")); + boolean exact = Boolean.parseBoolean(param.get("exact")); + if (part != null && !part.isBlank()) { + if (exact) { + model.getBone(part).ifPresent(bone -> bone.setEnchanted(enchant)); + } else { + for (Entry entry : model.getBones().entrySet()) { + if (entry.getKey().contains(part)) { + entry.getValue().setEnchanted(enchant); + } + } + } + } else { + for (ModelBone value : model.getBones().values()) { + value.setEnchanted(enchant); + } + } + } + + private void tag(ActiveModel model, Map param) { + String part = param.get("part"); + String tag = param.get("tag"); + boolean visible = Boolean.parseBoolean(param.getOrDefault("visible", "true")); + model.getBone(part).flatMap(modelBone -> modelBone.getBoneBehavior(BoneBehaviorTypes.NAMETAG)).ifPresent(nameTag -> { + ((NameTag)nameTag).setString(tag); + ((NameTag)nameTag).setVisible(visible); + }); + } + + private void changePart(ActiveModel model, Map param) { + String part = param.get("part"); + String nModel = param.get("nmodel"); + String nPart = param.get("npart"); + model.getBone(part).ifPresent(bone -> { + if (bone.isRenderer()) { + ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(nModel); + if (blueprint != null) { + BlueprintBone blueprintBone = blueprint.getFlatMap().get(nPart); + if (blueprintBone != null && blueprintBone.isRenderer()) { + bone.setModelScale(blueprintBone.getScale()); + bone.setModel(blueprintBone); + } + } + } + }); + } + + private void remap(ActiveModel model, Map param) { + String nModel = param.get("model"); + String map = param.get("map"); + ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(nModel); + if (blueprint != null) { + if (map != null) { + ModelBlueprint mapBlueprint = ModelEngineAPI.getBlueprint(map); + if (mapBlueprint == null) { + return; + } + + for (String bone : mapBlueprint.getFlatMap().keySet()) { + BlueprintBone blueprintBone = blueprint.getFlatMap().get(bone); + if (blueprintBone != null && blueprintBone.isRenderer()) { + model.getBone(bone).ifPresent(replaced -> { + if (replaced.isRenderer()) { + replaced.setModel(blueprintBone); + } + }); + } + } + } else { + for (String bonex : blueprint.getFlatMap().size() < model.getBones().size() ? blueprint.getFlatMap().keySet() : model.getBones().keySet()) { + BlueprintBone blueprintBone = blueprint.getFlatMap().get(bonex); + if (blueprintBone != null && blueprintBone.isRenderer()) { + model.getBone(bonex).ifPresent(replaced -> { + if (replaced.isRenderer()) { + replaced.setModelScale(blueprintBone.getScale()); + replaced.setModel(blueprintBone); + } + }); + } else { + TLogger.log(blueprint.getName() + ": " + bonex); + } + } + } + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/citizens/BugTrait.java b/core/src/main/java/com/ticxo/modelengine/core/citizens/BugTrait.java new file mode 100644 index 0000000..a3aa335 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/citizens/BugTrait.java @@ -0,0 +1,37 @@ +package com.ticxo.modelengine.core.citizens; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import net.citizensnpcs.api.trait.Trait; +import net.citizensnpcs.api.trait.TraitName; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.World; +import org.bukkit.Particle.DustOptions; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; + +@TraitName("bug") +public class BugTrait extends Trait { + private int tick; + + public BugTrait() { + super("bug"); + } + + public void run() { + Entity entity = this.npc.getEntity(); + if (entity != null) { + EntityHandler handler = ModelEngineAPI.getEntityHandler(); + Location location = entity.getLocation(); + World world = location.getWorld(); + Vector yRot = new Vector(0.0, 0.0, 0.5).rotateAroundY(-handler.getYRot(entity) * (float) (Math.PI / 180.0)); + Vector yBodyRot = new Vector(0, 0, 1).rotateAroundY(-handler.getYBodyRot(entity) * (float) (Math.PI / 180.0)); + Vector yHeadRot = new Vector(0.0, 0.0, 1.5).rotateAroundY(-handler.getYHeadRot(entity) * (float) (Math.PI / 180.0)); + world.spawnParticle(Particle.REDSTONE, location.clone().add(yRot), 1, new DustOptions(Color.RED, 0.25F)); + world.spawnParticle(Particle.REDSTONE, location.clone().add(yBodyRot), 1, new DustOptions(Color.GREEN, 0.25F)); + world.spawnParticle(Particle.REDSTONE, location.clone().add(yHeadRot), 1, new DustOptions(Color.BLUE, 0.25F)); + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/citizens/CitizensCommand.java b/core/src/main/java/com/ticxo/modelengine/core/citizens/CitizensCommand.java new file mode 100644 index 0000000..e4540db --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/citizens/CitizensCommand.java @@ -0,0 +1,394 @@ +package com.ticxo.modelengine.core.citizens; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.command.AbstractCommand; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core.command.MECommand; +import java.util.ArrayList; +import java.util.List; +import net.citizensnpcs.api.CitizensAPI; +import net.citizensnpcs.api.npc.NPC; +import net.citizensnpcs.api.npc.NPCRegistry; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +public class CitizensCommand extends AbstractCommand { + public CitizensCommand(AbstractCommand parent) { + super(parent); + this.addSubCommands(new AbstractCommand[]{new CitizensCommand.ModelCommand(this)}); + this.addSubCommands(new AbstractCommand[]{new CitizensCommand.StateCommand(this)}); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + return false; + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + return null; + } + + @Override + public String getPermissionNode() { + return "modelengine.command.npc"; + } + + @Override + public boolean isConsoleFriendly() { + return true; + } + + @Override + public String getName() { + return "npc"; + } + + private static void getNPCIdTabComplete(List list) { + CitizensAPI.getNPCRegistries().forEach(npcs -> npcs.sorted().forEach(npc -> { + if (npc.isSpawned() && npc.hasTrait(ModelTrait.class)) { + list.add(npcs.getName() + ":" + npc.getId() + ":[" + npc.getName().replace(" ", "-") + "]"); + } + })); + } + + private static String tryGetOrDefault(String[] args, int index, String def) { + return args.length <= index ? def : args[index]; + } + + private static NPC getNPC(String id) { + String[] val = id.split(":"); + if (val.length < 2) { + throw new IllegalArgumentException("NPC ID must be formatted as :"); + } else { + NPCRegistry reg = CitizensAPI.getNamedNPCRegistry(val[0]); + if (reg == null) { + throw new IllegalArgumentException("Unknown NPC registry: " + val[0]); + } else { + NPC npc = reg.getById(Integer.parseInt(val[1])); + if (npc == null) { + throw new IllegalArgumentException("Unknown NPC ID: " + val[1]); + } else { + return npc; + } + } + } + } + + private static class ModelCommand extends AbstractCommand { + public ModelCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + if (args.length < 1) { + return false; + } else { + NPC npc = CitizensCommand.getNPC(args[0]); + ModelTrait trait = (ModelTrait)npc.getTraitNullable(ModelTrait.class); + if (trait == null) { + return false; + } else if (!npc.isSpawned()) { + sender.sendMessage(ChatColor.RED + "Please spawn the NPC before editing."); + return true; + } else { + ModeledEntity modeledEntity = trait.getOrCreateModeledEntity(); + if (modeledEntity == null) { + sender.sendMessage(ChatColor.RED + "An error occurred while retrieving the model of this NPC."); + return true; + } else if (args.length >= 2) { + if (args.length >= 3) { + String modelId = args[2]; + String var13 = args[1]; + switch (var13) { + case "add": + boolean showBase = Boolean.parseBoolean(CitizensCommand.tryGetOrDefault(args, 3, "false")); + boolean overrideHitbox = Boolean.parseBoolean(CitizensCommand.tryGetOrDefault(args, 4, "true")); + ActiveModel model = ModelEngineAPI.createActiveModel(modelId); + if (model == null) { + return false; + } + + modeledEntity.setBaseEntityVisible(showBase); + modeledEntity.addModel(model, overrideHitbox).ifPresent(ActiveModel::destroy); + sender.sendMessage("Added model " + modelId + " to " + npc.getName()); + break; + case "remove": + modeledEntity.removeModel(modelId).ifPresent(ActiveModel::destroy); + if (modeledEntity.getModels().isEmpty()) { + modeledEntity.setBaseEntityVisible(true); + } + + sender.sendMessage("Removed model " + modelId + " from " + npc.getName()); + } + } + + return true; + } else if (modeledEntity.getModels().isEmpty()) { + sender.sendMessage("This NPC has no models."); + return true; + } else { + StringBuilder builder = new StringBuilder("Models: "); + + for (String active : modeledEntity.getModels().keySet()) { + builder.append(active).append(", "); + } + + builder.delete(builder.length() - 2, builder.length()); + sender.sendMessage(builder.toString()); + return true; + } + } + } + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + List list = new ArrayList<>(); + String arg = args[args.length - 1]; + switch (args.length) { + case 1: + CitizensCommand.getNPCIdTabComplete(list); + break; + case 2: + if ("add".startsWith(arg)) { + list.add("add"); + } + + if ("remove".startsWith(arg)) { + list.add("remove"); + } + break; + case 3: + String var5 = args[1]; + switch (var5) { + case "add": + MECommand.getModelIdTabComplete(list, arg); + return list; + case "remove": + ModelTrait trait = (ModelTrait)CitizensCommand.getNPC(args[0]).getTraitNullable(ModelTrait.class); + if (trait != null) { + MECommand.getModelIdTabComplete(list, arg, trait.getModeledEntity()); + } + + return list; + default: + return list; + } + case 4: + if ("add".equals(args[1])) { + list.add("[showBaseEntity]"); + if ("true".startsWith(arg)) { + list.add("true"); + } + + if ("false".startsWith(arg)) { + list.add("false"); + } + } + break; + case 5: + if ("add".equals(args[1])) { + list.add("[overrideHitbox]"); + if ("true".startsWith(arg)) { + list.add("true"); + } + + if ("false".startsWith(arg)) { + list.add("false"); + } + } + } + + return list; + } + + @Override + public String getPermissionNode() { + return "modelengine.command.npc.model"; + } + + @Override + public boolean isConsoleFriendly() { + return true; + } + + @Override + public String getName() { + return "model"; + } + } + + private static class StateCommand extends AbstractCommand { + public StateCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + if (args.length < 1) { + return false; + } else { + NPC npc = CitizensCommand.getNPC(args[0]); + ModelTrait trait = (ModelTrait)npc.getTraitNullable(ModelTrait.class); + if (trait == null) { + return false; + } else if (!npc.isSpawned()) { + sender.sendMessage(ChatColor.RED + "Please spawn the NPC before editing."); + return true; + } else { + ModeledEntity modeledEntity = trait.getOrCreateModeledEntity(); + if (modeledEntity == null) { + sender.sendMessage(ChatColor.RED + "An error occurred while retrieving the model of this NPC."); + return true; + } else { + ActiveModel activeModel = modeledEntity.getModel(args[1]).orElse(null); + if (activeModel == null) { + return false; + } else if (args.length >= 3) { + if (args.length < 4) { + return false; + } else { + String stateId = args[3]; + String var15 = args[2]; + switch (var15) { + case "add": + if (!activeModel.getBlueprint().getAnimations().containsKey(stateId)) { + return false; + } + + int lerpIn = Integer.parseInt(CitizensCommand.tryGetOrDefault(args, 4, "0")); + int lerpOut = Integer.parseInt(CitizensCommand.tryGetOrDefault(args, 5, "0")); + double speed = Double.parseDouble(CitizensCommand.tryGetOrDefault(args, 6, "1")); + activeModel.getAnimationHandler().playAnimation(stateId, lerpIn / 20.0, lerpOut / 20.0, speed, true); + sender.sendMessage("Added state " + stateId + " to " + npc.getName()); + break; + case "remove": + boolean ignoreLerp = Boolean.parseBoolean(CitizensCommand.tryGetOrDefault(args, 4, "false")); + if (ignoreLerp) { + activeModel.getAnimationHandler().forceStopAnimation(stateId); + } else { + activeModel.getAnimationHandler().forceStopAnimation(stateId); + } + + sender.sendMessage("Removed state " + stateId + " from " + npc.getName()); + } + + return false; + } + } else { + StringBuilder builder = new StringBuilder(); + builder.append(args[1]).append(": "); + + for (IAnimationProperty animation : activeModel.getAnimationHandler().getAnimations().values()) { + builder.append(animation.getName()).append(", "); + } + + builder.delete(builder.length() - 2, builder.length()); + sender.sendMessage(builder.toString()); + return true; + } + } + } + } + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + List list = new ArrayList<>(); + String arg = args[args.length - 1]; + switch (args.length) { + case 1: + CitizensCommand.getNPCIdTabComplete(list); + break; + case 2: + ModelTrait traitx = (ModelTrait)CitizensCommand.getNPC(args[0]).getTraitNullable(ModelTrait.class); + if (traitx != null) { + MECommand.getModelIdTabComplete(list, arg, traitx.getModeledEntity()); + } + break; + case 3: + if ("add".startsWith(arg)) { + list.add("add"); + } + + if ("remove".startsWith(arg)) { + list.add("remove"); + } + break; + case 4: + ModelTrait trait = (ModelTrait)CitizensCommand.getNPC(args[0]).getTraitNullable(ModelTrait.class); + if (trait == null) { + return list; + } + + ModeledEntity model = trait.getModeledEntity(); + ActiveModel activeModel = model.getModel(args[1]).orElse(null); + if (activeModel == null) { + return list; + } + + String var8 = args[2]; + switch (var8) { + case "add": + MECommand.getStateTabComplete(list, arg, activeModel.getBlueprint()); + return list; + case "remove": + MECommand.getStateTabComplete(list, arg, activeModel); + return list; + default: + return list; + } + case 5: + String traitAction = args[2]; + switch (traitAction) { + case "add": + list.add("[lerpin]"); + return list; + case "remove": + list.add("[ignoreLerp]"); + if ("true".startsWith(arg)) { + list.add("true"); + } + + if ("false".startsWith(arg)) { + list.add("false"); + } + + return list; + default: + return list; + } + case 6: + if ("add".equals(args[2])) { + list.add("[lerpout]"); + } + break; + case 7: + if ("add".equals(args[2])) { + list.add("[speed]"); + } + } + + return list; + } + + @Override + public String getPermissionNode() { + return "modelengine.command.npc.state"; + } + + @Override + public boolean isConsoleFriendly() { + return true; + } + + @Override + public String getName() { + return "state"; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/citizens/ModelTrait.java b/core/src/main/java/com/ticxo/modelengine/core/citizens/ModelTrait.java new file mode 100644 index 0000000..ceda139 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/citizens/ModelTrait.java @@ -0,0 +1,68 @@ +package com.ticxo.modelengine.core.citizens; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import com.ticxo.modelengine.core.data.DataUpdater; +import net.citizensnpcs.api.trait.Trait; +import net.citizensnpcs.api.trait.TraitName; +import net.citizensnpcs.api.util.DataKey; +import org.bukkit.Location; +import org.bukkit.entity.Entity; + +@TraitName("meg_model") +public class ModelTrait extends Trait { + private String modelData; + + public ModelTrait() { + super("meg_model"); + } + + public void load(DataKey key) { + this.modelData = key.getString("model_data"); + } + + public void save(DataKey key) { + ModeledEntity modeledEntity = this.getModeledEntity(); + if (modeledEntity != null) { + modeledEntity.save().ifPresent(data -> this.modelData = data.toString()); + } else { + this.modelData = null; + } + + key.setString("model_data", this.modelData); + } + + public void onDespawn() { + ModeledEntity modeledEntity = this.getModeledEntity(); + if (modeledEntity != null) { + modeledEntity.save().ifPresent(data -> this.modelData = data.toString()); + } else { + this.modelData = null; + } + } + + public void onSpawn() { + if (this.modelData != null) { + Entity entity = this.getNPC().getEntity(); + Location location = entity.getLocation(); + SavedData data = DataUpdater.convertToSavedData(location, this.modelData); + if (DataUpdater.tryUpdate(data)) { + BukkitEntity base = new BukkitEntity(entity); + base.getBodyRotationController().setYBodyRot(location.getYaw()); + ModeledEntity modeledEntity = ModelEngineAPI.createModeledEntity(base); + modeledEntity.setSaved(false); + modeledEntity.load(data); + } + } + } + + public ModeledEntity getModeledEntity() { + return this.npc.getEntity() != null ? ModelEngineAPI.getModeledEntity(this.npc.getEntity()) : null; + } + + public ModeledEntity getOrCreateModeledEntity() { + return this.npc.getEntity() != null ? ModelEngineAPI.getOrCreateModeledEntity(this.npc.getEntity()) : null; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/MECommand.java b/core/src/main/java/com/ticxo/modelengine/core/command/MECommand.java new file mode 100644 index 0000000..fe676d7 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/MECommand.java @@ -0,0 +1,106 @@ +package com.ticxo.modelengine.core.command; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.command.AbstractCommand; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.core.command.sub.DebugCommand; +import com.ticxo.modelengine.core.command.sub.DisguiseCommand; +import com.ticxo.modelengine.core.command.sub.MenuCommand; +import com.ticxo.modelengine.core.command.sub.PluginHealthCommand; +import com.ticxo.modelengine.core.command.sub.ReloadCommand; +import com.ticxo.modelengine.core.command.sub.ResyncCommand; +import com.ticxo.modelengine.core.command.sub.SummonCommand; +import com.ticxo.modelengine.core.command.sub.ToggleLODCommand; +import com.ticxo.modelengine.core.command.sub.UndisguiseCommand; +import java.util.List; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Entity; + +public class MECommand extends AbstractCommand { + public MECommand(ModelEngineAPI plugin) { + super(plugin); + this.addSubCommands(new AbstractCommand[]{new ReloadCommand(this)}); + this.addSubCommands(new AbstractCommand[]{new SummonCommand(this)}); + this.addSubCommands(new AbstractCommand[]{new DisguiseCommand(this)}); + this.addSubCommands(new AbstractCommand[]{new UndisguiseCommand(this)}); + this.addSubCommands(new AbstractCommand[]{new DebugCommand(this)}); + this.addSubCommands(new AbstractCommand[]{new MenuCommand(this)}); + this.addSubCommands(new AbstractCommand[]{new PluginHealthCommand(this)}); + this.addSubCommands(new AbstractCommand[]{new ResyncCommand(this)}); + this.addSubCommands(new AbstractCommand[]{new ToggleLODCommand(this)}); + } + + public static void getModelIdTabComplete(List list, String arg) { + for (String id : ModelEngineAPI.getAPI().getModelRegistry().getKeys()) { + if (id.startsWith(arg)) { + list.add(id); + } + } + } + + public static void getModelIdTabComplete(List list, String arg, ModeledEntity modeledEntity) { + for (String id : modeledEntity.getModels().keySet()) { + if (id.startsWith(arg)) { + list.add(id); + } + } + } + + public static void getStateTabComplete(List list, String arg, ActiveModel model) { + for (IAnimationProperty animation : model.getAnimationHandler().getAnimations().values()) { + String name = animation.getName(); + if (name.startsWith(arg)) { + list.add(name); + } + } + } + + public static void getStateTabComplete(List list, String arg, ModelBlueprint blueprint) { + for (String animation : blueprint.getAnimations().keySet()) { + if (animation.startsWith(arg)) { + list.add(animation); + } + } + } + + public static void logSender(CommandSender sender, String msg) { + logSender(sender, msg, msg); + } + + public static void logSender(CommandSender sender, String entityMsg, String consoleMsg) { + if (sender instanceof Entity) { + sender.sendMessage(entityMsg); + } else { + TLogger.log(consoleMsg); + } + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + return false; + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + return null; + } + + @Override + public String getPermissionNode() { + return "modelengine.command"; + } + + @Override + public boolean isConsoleFriendly() { + return true; + } + + @Override + public String getName() { + return null; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/ModelOptionParser.java b/core/src/main/java/com/ticxo/modelengine/core/command/ModelOptionParser.java new file mode 100644 index 0000000..d36447b --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/ModelOptionParser.java @@ -0,0 +1,210 @@ +package com.ticxo.modelengine.core.command; + +import com.ticxo.modelengine.api.model.ActiveModel; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.bukkit.Color; + +public final class ModelOptionParser { + private Boolean doDamageTint; + private Boolean lockPitch; + private Boolean lockYaw; + private Boolean showHitbox; + private Boolean showShadow; + private Double stepHeight; + private Double scale; + private Double hitboxScale; + private Integer viewRadius; + private Color color; + public Boolean hideSelf = true; + public Boolean hideSelfDisguise = false; + public Boolean pivotOverride = true; + + public static ModelOptionParser parse(int offset, String[] argss) { + ModelOptionParser options = new ModelOptionParser(); + if (argss.length <= offset) { + return options; + } else { + String[] args = Arrays.copyOfRange(argss, offset, argss.length); + + for (int i = 0; i < args.length; i++) { + String var5 = args[i].toLowerCase(); + switch (var5) { + case "dodamagetint": + options.doDamageTint = getNextBoolean(args, ++i); + break; + case "lockpitch": + options.lockPitch = getNextBoolean(args, ++i); + break; + case "lockyaw": + options.lockYaw = getNextBoolean(args, ++i); + break; + case "showhitbox": + options.showHitbox = getNextBoolean(args, ++i); + break; + case "showshadow": + options.showShadow = getNextBoolean(args, ++i); + break; + case "stepheight": + options.stepHeight = getNextDouble(args, ++i); + break; + case "scale": + options.scale = getNextDouble(args, ++i); + break; + case "hitboxscale": + options.hitboxScale = getNextDouble(args, ++i); + break; + case "viewradius": + options.viewRadius = getNextInteger(args, ++i); + break; + case "hideself": + options.hideSelf = getNextBoolean(args, ++i); + break; + case "hideselfdisguise": + options.hideSelfDisguise = getNextBoolean(args, ++i); + break; + case "color": + String colorString = getNextString(args, ++i); + if (colorString.startsWith("#")) { + colorString = colorString.substring(1); + } + + options.color = Color.fromRGB(Integer.parseInt(colorString, 16)); + break; + case "pivotoverride": + options.pivotOverride = getNextBoolean(args, ++i); + } + } + + return options; + } + } + + public static List getTabCompletion(int offset, String[] argss) { + String[] args = Arrays.copyOfRange(argss, offset, argss.length); + List completions = new ArrayList<>(); + if (args.length == 1) { + completions.addAll( + Arrays.asList( + "doDamageTint", + "lockPitch", + "lockYaw", + "showHitbox", + "showShadow", + "stepHeight", + "scale", + "hitboxScale", + "viewRadius", + "hideSelfDisguise", + "color", + "pivotOverride", + "hideSelf" + ) + ); + return completions; + } else { + String lastArg = args[args.length - 2].toLowerCase(); + if (!isValueExpected(lastArg)) { + completions.addAll( + Arrays.asList( + "doDamageTint", + "lockPitch", + "lockYaw", + "showHitbox", + "showShadow", + "stepHeight", + "scale", + "hitboxScale", + "viewRadius", + "hideSelfDisguise", + "color", + "pivotOverride", + "hideSelf" + ) + ); + } + + return completions; + } + } + + private static boolean isValueExpected(String lastArg) { + return lastArg.matches("stepheight|scale|hitboxscale|viewradius|color"); + } + + public void applyDisguiseOptions(ActiveModel activeModel) { + if (this.scale != null) { + activeModel.setScale(this.scale); + } + + if (this.hitboxScale != null) { + activeModel.setHitboxScale(this.hitboxScale); + } + + if (this.doDamageTint != null) { + activeModel.setCanHurt(this.doDamageTint); + } + + if (this.lockPitch != null) { + activeModel.setLockPitch(this.lockPitch); + } + + if (this.lockYaw != null) { + activeModel.setLockYaw(this.lockYaw); + } + + if (this.showHitbox != null) { + activeModel.setHitboxVisible(this.showHitbox); + } + + if (this.showShadow != null) { + activeModel.setShadowVisible(this.showShadow); + } + + if (this.viewRadius != null) { + activeModel.getModeledEntity().getBase().setRenderRadius(this.viewRadius); + } + + if (this.stepHeight != null) { + activeModel.getModeledEntity().getBase().setMaxStepHeight(this.stepHeight); + } + + if (this.color != null) { + activeModel.setDefaultTint(this.color); + } + } + + private static Boolean getNextBoolean(String[] args, int index) { + if (index >= args.length) { + return true; + } else { + String nextArg = args[index].toLowerCase(); + return nextArg.equals("true") || !nextArg.equals("false"); + } + } + + private static Double getNextDouble(String[] args, int index) { + try { + return index < args.length ? Double.parseDouble(args[index]) : null; + } catch (NumberFormatException var3) { + return null; + } + } + + private static Integer getNextInteger(String[] args, int index) { + try { + return index < args.length ? Integer.parseInt(args[index]) : null; + } catch (NumberFormatException var3) { + return null; + } + } + + private static String getNextString(String[] args, int index) { + try { + return index < args.length ? args[index] : null; + } catch (NumberFormatException var3) { + return null; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/sub/DebugCommand.java b/core/src/main/java/com/ticxo/modelengine/core/command/sub/DebugCommand.java new file mode 100644 index 0000000..21be01a --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/sub/DebugCommand.java @@ -0,0 +1,77 @@ +package com.ticxo.modelengine.core.command.sub; + +import com.ticxo.modelengine.api.command.AbstractCommand; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.LogColor; +import com.ticxo.modelengine.core.command.MECommand; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +public class DebugCommand extends AbstractCommand { + public DebugCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + if (args.length == 0) { + return false; + } else { + DebugToggle debugToggle = DebugToggle.get(args[0]); + if (debugToggle == null) { + MECommand.logSender(sender, ChatColor.RED + "[ModelEngine] Unknown debug: " + args[0] + ".", LogColor.RED + "Unknown debug: " + args[0] + "."); + return false; + } else if (args.length == 1) { + MECommand.logSender( + sender, + ChatColor.GREEN + "[ModelEngine] " + debugToggle.name() + " is " + (DebugToggle.isDebugging(debugToggle) ? "enabled." : "disabled."), + LogColor.BRIGHT_GREEN + debugToggle.name() + " is " + (DebugToggle.isDebugging(debugToggle) ? "enabled." : "disabled.") + ); + return true; + } else { + boolean flag = Boolean.parseBoolean(args[1]); + DebugToggle.setDebug(debugToggle, flag); + MECommand.logSender( + sender, + ChatColor.GREEN + "[ModelEngine] Set " + debugToggle.name() + " to " + flag + ".", + LogColor.BRIGHT_GREEN + "Set " + debugToggle.name() + " to " + flag + "." + ); + return true; + } + } + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + ArrayList list = new ArrayList<>(); + switch (args.length) { + case 1: + for (DebugToggle debug : DebugToggle.values()) { + list.add(debug.name()); + } + break; + case 2: + list.add("true"); + list.add("false"); + } + + return list; + } + + @Override + public String getPermissionNode() { + return "modelengine.command.debug"; + } + + @Override + public boolean isConsoleFriendly() { + return true; + } + + @Override + public String getName() { + return "debug"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/sub/DisguiseCommand.java b/core/src/main/java/com/ticxo/modelengine/core/command/sub/DisguiseCommand.java new file mode 100644 index 0000000..43f1d62 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/sub/DisguiseCommand.java @@ -0,0 +1,93 @@ +package com.ticxo.modelengine.core.command.sub; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.command.AbstractCommand; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.type.PlayerLimb; +import com.ticxo.modelengine.api.model.bone.type.UserLimb; +import com.ticxo.modelengine.core.command.MECommand; +import com.ticxo.modelengine.core.command.ModelOptionParser; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class DisguiseCommand extends AbstractCommand { + public DisguiseCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + Player player = (Player)sender; + if (args.length < 1) { + return false; + } else { + ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(args[0]); + if (blueprint == null) { + return false; + } else { + ModelOptionParser options = ModelOptionParser.parse(1, args); + ModeledEntity modeledEntity = ModelEngineAPI.getOrCreateModeledEntity(player); + modeledEntity.getBase().getBodyRotationController().setPlayerMode(true); + modeledEntity.setBaseEntityVisible(!options.hideSelf); + if (modeledEntity.getBase().getData() instanceof BukkitEntityData data && (args.length < 2 || !options.hideSelfDisguise)) { + data.getTracked().addForcedPairing(player.getUniqueId()); + } + + if (options.hideSelf) { + ModelEngineAPI.getEntityHandler().setForcedInvisible(player, true); + } + + if (modeledEntity.getModel(args[0]).isEmpty()) { + ActiveModel activeModel = ModelEngineAPI.createActiveModel(blueprint); + options.applyDisguiseOptions(activeModel); + modeledEntity.addModel(activeModel, false).ifPresent(ActiveModel::destroy); + if (options.pivotOverride) { + activeModel.setPivotOverride(ModelEngineAPI.getPivotOverrideRegistry().getOrCreate(player)); + } + + activeModel.getBones().values().forEach(modelBone -> { + modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(playerLimb -> ((PlayerLimb)playerLimb).setTexture(player)); + modelBone.getBoneBehavior(BoneBehaviorTypes.USER_LIMB).ifPresent(playerLimb -> ((UserLimb)playerLimb).setTexture(player)); + }); + } + + return true; + } + } + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + List list = new ArrayList<>(); + switch (args.length) { + case 1: + MECommand.getModelIdTabComplete(list, args[0]); + break; + default: + list.addAll(ModelOptionParser.getTabCompletion(1, args)); + } + + return list; + } + + @Override + public String getPermissionNode() { + return "modelengine.command.disguise"; + } + + @Override + public boolean isConsoleFriendly() { + return false; + } + + @Override + public String getName() { + return "disguise"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/sub/MenuCommand.java b/core/src/main/java/com/ticxo/modelengine/core/command/sub/MenuCommand.java new file mode 100644 index 0000000..42b4649 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/sub/MenuCommand.java @@ -0,0 +1,42 @@ +package com.ticxo.modelengine.core.command.sub; + +import com.ticxo.modelengine.api.command.AbstractCommand; +import com.ticxo.modelengine.core.menu.screen.NavigationScreen; +import java.util.List; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class MenuCommand extends AbstractCommand { + public MenuCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + if (sender instanceof Player player) { + new NavigationScreen(player).openScreen(); + } + + return true; + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + return null; + } + + @Override + public String getPermissionNode() { + return "modelengine.command.menu"; + } + + @Override + public boolean isConsoleFriendly() { + return false; + } + + @Override + public String getName() { + return "menu"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/sub/PluginHealthCommand.java b/core/src/main/java/com/ticxo/modelengine/core/command/sub/PluginHealthCommand.java new file mode 100644 index 0000000..d0ad43f --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/sub/PluginHealthCommand.java @@ -0,0 +1,57 @@ +package com.ticxo.modelengine.core.command.sub; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.command.AbstractCommand; +import com.ticxo.modelengine.api.entity.EntityDataTrackers; +import com.ticxo.modelengine.api.utils.Profiler; +import com.ticxo.modelengine.core.command.MECommand; +import java.util.List; +import org.bukkit.command.CommandSender; + +public class PluginHealthCommand extends AbstractCommand { + public PluginHealthCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + Profiler updaterProfiler = ModelEngineAPI.getAPI().getModelUpdaters().getProfiler(); + MECommand.logSender( + sender, + String.format( + "Model Updaters: Min: %.3f ms, Max: %.3f ms, Avg: %.3f ms", + updaterProfiler.getMinTime() / 1000000.0, + updaterProfiler.getMaxTime() / 1000000.0, + updaterProfiler.getAverageTime() / 1000000.0 + ) + ); + EntityDataTrackers trackers = ModelEngineAPI.getAPI().getDataTrackers(); + MECommand.logSender(sender, "Entity Data Trackers:"); + + for (EntityDataTrackers.Tracker tracker : trackers.getAvailable()) { + MECommand.logSender(sender, String.format("- %s: %s (%sms)", tracker.getId(), tracker.getLoad(), tracker.getTimings())); + } + + return true; + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + return null; + } + + @Override + public String getPermissionNode() { + return "modelengine.command.health"; + } + + @Override + public boolean isConsoleFriendly() { + return true; + } + + @Override + public String getName() { + return "health"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/sub/ReloadCommand.java b/core/src/main/java/com/ticxo/modelengine/core/command/sub/ReloadCommand.java new file mode 100644 index 0000000..1e7ab79 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/sub/ReloadCommand.java @@ -0,0 +1,94 @@ +package com.ticxo.modelengine.core.command.sub; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.command.AbstractCommand; +import com.ticxo.modelengine.api.generator.ModelGenerator; +import com.ticxo.modelengine.api.generator.skin.SkinSplitter; +import com.ticxo.modelengine.api.utils.config.ConfigManager; +import com.ticxo.modelengine.api.utils.logger.LogColor; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.core.command.MECommand; +import java.util.List; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Entity; + +public class ReloadCommand extends AbstractCommand { + public ReloadCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + if (args.length == 0) { + this.reloadConfig(sender); + this.reloadModels(sender); + this.reloadMappings(sender); + return true; + } else { + String var3 = args[0]; + switch (var3) { + case "models": + this.reloadModels(sender); + break; + case "config": + this.reloadConfig(sender); + break; + case "mappings": + this.reloadMappings(sender); + break; + default: + return false; + } + + return true; + } + } + + private void reloadConfig(CommandSender sender) { + ConfigManager config = ModelEngineAPI.getAPI().getConfigManager(); + config.reload(); + config.updateReferences(); + MECommand.logSender(sender, ChatColor.GREEN + "[ModelEngine] Config reloaded.", LogColor.BRIGHT_GREEN + "Config reloaded."); + } + + private void reloadModels(CommandSender sender) { + ModelGenerator generator = ModelEngineAPI.getAPI().getModelGenerator(); + generator.importModels(false); + generator.queueTask(ModelGenerator.Phase.POST_IMPORT, () -> { + String msg = ModelEngineAPI.getAPI().getModelRegistry().getKeys().size() + " models loaded."; + if (sender instanceof Entity) { + sender.sendMessage(ChatColor.GREEN + "[ModelEngine] " + msg); + } else { + TLogger.log(); + TLogger.log(LogColor.BRIGHT_GREEN + msg); + } + }); + } + + private void reloadMappings(CommandSender sender) { + SkinSplitter generator = ModelEngineAPI.getAPI().getSkinSplitter(); + generator.reloadMapping(); + MECommand.logSender(sender, ChatColor.GREEN + "[ModelEngine] Skin mappings reloaded.", LogColor.BRIGHT_GREEN + "Skin mappings reloaded."); + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + return List.of("models", "config", "mappings"); + } + + @Override + public String getPermissionNode() { + return "modelengine.command.reload"; + } + + @Override + public boolean isConsoleFriendly() { + return true; + } + + @Override + public String getName() { + return "reload"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/sub/ResyncCommand.java b/core/src/main/java/com/ticxo/modelengine/core/command/sub/ResyncCommand.java new file mode 100644 index 0000000..f75a984 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/sub/ResyncCommand.java @@ -0,0 +1,48 @@ +package com.ticxo.modelengine.core.command.sub; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.command.AbstractCommand; +import java.util.List; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class ResyncCommand extends AbstractCommand { + public ResyncCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + if (sender instanceof Player player) { + ModelEngineAPI.getNetworkHandler().getPipeline(player.getUniqueId()).ifPresent(wrapper -> { + if (args.length >= 1) { + wrapper.setDelay(Long.parseLong(args[0])); + } else { + wrapper.getDesyncMonitor().startTest(); + } + }); + } + + return true; + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + return null; + } + + @Override + public String getPermissionNode() { + return "modelengine.command.resync"; + } + + @Override + public boolean isConsoleFriendly() { + return true; + } + + @Override + public String getName() { + return "resync"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/sub/SummonCommand.java b/core/src/main/java/com/ticxo/modelengine/core/command/sub/SummonCommand.java new file mode 100644 index 0000000..7a111dd --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/sub/SummonCommand.java @@ -0,0 +1,111 @@ +package com.ticxo.modelengine.core.command.sub; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.command.AbstractCommand; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.type.PlayerLimb; +import com.ticxo.modelengine.api.model.bone.type.UserLimb; +import com.ticxo.modelengine.core.command.MECommand; +import com.ticxo.modelengine.core.command.ModelOptionParser; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; + +public class SummonCommand extends AbstractCommand { + public SummonCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + if (args.length < 1) { + return false; + } else { + EntityType type = EntityType.PIG; + if (args.length >= 2) { + try { + type = EntityType.valueOf(args[1].toUpperCase(Locale.ENGLISH)); + } catch (IllegalArgumentException var9) { + } + } + + Class clazz = type.getEntityClass(); + if (clazz == null) { + return false; + } else { + ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(args[0]); + if (blueprint == null) { + return false; + } else { + ModelOptionParser options = ModelOptionParser.parse(2, args); + Player player = (Player)sender; + Location location = player.getLocation(); + player.getWorld().spawn(location, clazz, entity -> { + BukkitEntity base = new BukkitEntity(entity); + base.getBodyRotationController().setYBodyRot(location.getYaw()); + ModeledEntity modeledEntity = ModelEngineAPI.createModeledEntity(base); + modeledEntity.setBaseEntityVisible(false); + ActiveModel activeModel = ModelEngineAPI.createActiveModel(blueprint); + activeModel.setAutoRendererInitialization(false); + options.applyDisguiseOptions(activeModel); + modeledEntity.addModel(activeModel, true).ifPresent(ActiveModel::destroy); + activeModel.getBones().values().forEach(modelBone -> { + modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(playerLimb -> ((PlayerLimb)playerLimb).setTexture(player)); + modelBone.getBoneBehavior(BoneBehaviorTypes.USER_LIMB).ifPresent(userLimb -> ((UserLimb)userLimb).setTexture(player)); + }); + activeModel.initializeRenderer(); + }); + return true; + } + } + } + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + List list = new ArrayList<>(); + switch (args.length) { + case 1: + MECommand.getModelIdTabComplete(list, args[0]); + break; + case 2: + String arg = args[1]; + + for (EntityType type : EntityType.values()) { + String name = type.name(); + if (name.startsWith(arg.toUpperCase(Locale.ENGLISH))) { + list.add(name); + } + } + break; + default: + list.addAll(ModelOptionParser.getTabCompletion(args.length > 1 ? 2 : 1, args)); + } + + return list; + } + + @Override + public String getPermissionNode() { + return "modelengine.command.summon"; + } + + @Override + public boolean isConsoleFriendly() { + return false; + } + + @Override + public String getName() { + return "summon"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/sub/TestCommand.java b/core/src/main/java/com/ticxo/modelengine/core/command/sub/TestCommand.java new file mode 100644 index 0000000..5bc4546 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/sub/TestCommand.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.core.command.sub; + +import com.ticxo.modelengine.api.command.AbstractCommand; +import java.util.List; +import org.bukkit.command.CommandSender; + +public class TestCommand extends AbstractCommand { + public TestCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + return true; + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + return null; + } + + @Override + public String getPermissionNode() { + return "modelengine.command.test"; + } + + @Override + public boolean isConsoleFriendly() { + return false; + } + + @Override + public String getName() { + return "test"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/sub/ToggleLODCommand.java b/core/src/main/java/com/ticxo/modelengine/core/command/sub/ToggleLODCommand.java new file mode 100644 index 0000000..76d2d50 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/sub/ToggleLODCommand.java @@ -0,0 +1,58 @@ +package com.ticxo.modelengine.core.command.sub; + +import com.ticxo.modelengine.api.command.AbstractCommand; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.utils.logger.LogColor; +import com.ticxo.modelengine.core.command.MECommand; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +public class ToggleLODCommand extends AbstractCommand { + public ToggleLODCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + if (args.length >= 1) { + AnimationLODHandler.setGlobalEnabled(Boolean.parseBoolean(args[0])); + } else { + MECommand.logSender( + sender, + ChatColor.GREEN + "[ModelEngine] Animation LOD is " + (AnimationLODHandler.isGlobalEnabled() ? "enabled." : "disabled."), + LogColor.BRIGHT_GREEN + "Animation LOD is " + (AnimationLODHandler.isGlobalEnabled() ? "enabled." : "disabled.") + ); + } + + return true; + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + if (args.length != 1) { + return null; + } else { + ArrayList list = new ArrayList<>(); + list.add("true"); + list.add("false"); + return list; + } + } + + @Override + public String getPermissionNode() { + return "modelengine.command.toggle-lod"; + } + + @Override + public boolean isConsoleFriendly() { + return true; + } + + @Override + public String getName() { + return "toggle-lod"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/command/sub/UndisguiseCommand.java b/core/src/main/java/com/ticxo/modelengine/core/command/sub/UndisguiseCommand.java new file mode 100644 index 0000000..4f82d3f --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/command/sub/UndisguiseCommand.java @@ -0,0 +1,76 @@ +package com.ticxo.modelengine.core.command.sub; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.command.AbstractCommand; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core.command.MECommand; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class UndisguiseCommand extends AbstractCommand { + public UndisguiseCommand(AbstractCommand parent) { + super(parent); + } + + @Override + public boolean onCommand(CommandSender sender, String[] args) { + Player player = (Player)sender; + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(player.getUniqueId()); + if (modeledEntity == null) { + return true; + } else { + if (args.length == 0) { + modeledEntity.setBaseEntityVisible(true); + modeledEntity.markRemoved(); + ModelEngineAPI.getEntityHandler().setForcedInvisible(player, false); + } else { + for (String modelId : args) { + modeledEntity.removeModel(modelId).ifPresent(ActiveModel::destroy); + } + + if (modeledEntity.getModels().isEmpty()) { + modeledEntity.setBaseEntityVisible(true); + modeledEntity.markRemoved(); + ModelEngineAPI.getEntityHandler().setForcedInvisible(player, false); + } + } + + return true; + } + } + + @Override + public List onTabComplete(CommandSender sender, String[] args) { + List list = new ArrayList<>(); + Player player = (Player)sender; + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(player.getUniqueId()); + if (modeledEntity == null) { + return list; + } else { + if (args.length > 0) { + String arg = args[args.length - 1]; + MECommand.getModelIdTabComplete(list, arg, modeledEntity); + } + + return list; + } + } + + @Override + public String getPermissionNode() { + return "modelengine.command.undisguise"; + } + + @Override + public boolean isConsoleFriendly() { + return false; + } + + @Override + public String getName() { + return "undisguise"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/data/DataUpdater.java b/core/src/main/java/com/ticxo/modelengine/core/data/DataUpdater.java new file mode 100644 index 0000000..35da2ee --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/data/DataUpdater.java @@ -0,0 +1,67 @@ +package com.ticxo.modelengine.core.data; + +import com.google.gson.Gson; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import org.bukkit.Location; +import org.jetbrains.annotations.Nullable; + +public class DataUpdater { + private static final Map> VERSION_CHAIN = new HashMap>() { + { + this.put("R4.0.0", data -> { + data.putString("version", "R4.0.3"); + List list = data.getList("models", SavedData.class); + + for (SavedData modelData : list) { + modelData.putBoolean("hitbox_visible", true); + modelData.putBoolean("shadow_visible", true); + modelData.putBoolean("main_hitbox", true); + } + + data.putList("models", list); + }); + } + }; + + @Nullable + public static SavedData convertToSavedData(@Nullable Location location, String json) { + if (json != null && !json.isEmpty() && !json.isBlank()) { + Gson gson = ModelEngineAPI.getAPI().getGson(); + SavedData data = (SavedData)gson.fromJson(json, SavedData.class); + if (data == null) { + return null; + } else { + if (data.getString("version") == null) { + V3Data oldData = (V3Data)gson.fromJson(json, V3Data.class); + data = oldData.convert(location); + } + + return data; + } + } else { + return null; + } + } + + public static boolean tryUpdate(@Nullable SavedData data) { + if (data == null) { + return false; + } else if (data.getString("version") == null) { + return false; + } else { + while (true) { + Consumer updater = VERSION_CHAIN.get(data.getString("version")); + if (updater == null) { + return true; + } + + updater.accept(data); + } + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/data/V3Data.java b/core/src/main/java/com/ticxo/modelengine/core/data/V3Data.java new file mode 100644 index 0000000..cd59b54 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/data/V3Data.java @@ -0,0 +1,752 @@ +package com.ticxo.modelengine.core.data; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.BlueprintAnimation; +import com.ticxo.modelengine.api.animation.ModelState; +import com.ticxo.modelengine.api.animation.handler.AnimationHandler; +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.animation.property.SimpleProperty; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Dummy; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.nms.impl.DefaultBodyRotationController; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import com.ticxo.modelengine.core.model.ModeledEntityImpl; +import java.util.Map; +import java.util.function.Consumer; +import org.bukkit.Location; +import org.jetbrains.annotations.Nullable; + +public class V3Data { + private int renderDistance; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle; + private int rotationDelay; + private int rotationDuration; + private boolean canSteer; + private boolean canRide; + private String mountModelId; + private String mountDriverBone; + private boolean isBaseEntityVisible; + private boolean modelRotationLock; + private Double stepHeight; + private Hitbox hitbox; + private final Map models = Maps.newConcurrentMap(); + + public SavedData convert(@Nullable Location location) { + Dummy dummy = new Dummy<>(); + dummy.setRenderRadius(this.renderDistance); + dummy.setLocation(location); + if (this.stepHeight != null) { + dummy.setMaxStepHeight(this.stepHeight); + } + + DefaultBodyRotationController bodyController = dummy.getBodyRotationController(); + bodyController.setHeadClampUneven(this.isHeadClampUneven); + bodyController.setBodyClampUneven(this.isBodyClampUneven); + bodyController.setMaxHeadAngle(this.maxHeadAngle); + bodyController.setMaxBodyAngle(this.maxBodyAngle); + bodyController.setMinHeadAngle(this.minHeadAngle); + bodyController.setMinBodyAngle(this.minBodyAngle); + bodyController.setPlayerMode(this.playerMode); + bodyController.setStableAngle(this.stableAngle); + bodyController.setRotationDelay(this.rotationDelay); + bodyController.setRotationDuration(this.rotationDuration); + var modeledEntity = new ModeledEntityImpl(dummy, null) { + @Override + public void registerSelf() { + } + }; + modeledEntity.setBaseEntityVisible(this.isBaseEntityVisible); + modeledEntity.setModelRotationLocked(this.modelRotationLock); + this.models + .forEach( + (modelId, modelData) -> { + ActiveModel activeModel = ModelEngineAPI.createActiveModel(modelId); + if (activeModel != null) { + activeModel.setCanHurt(modelData.canHurt); + activeModel.setLockPitch(modelData.lockPitch); + activeModel.setLockYaw(modelData.lockYaw); + modelData.defaultStates + .forEach( + (modelState, property) -> activeModel.getAnimationHandler() + .setDefaultProperty( + new AnimationHandler.DefaultProperty(modelState, property.stateId, property.lerpIn, property.lerpOut, property.speed) + ) + ); + ModelBlueprint blueprint = activeModel.getBlueprint(); + modelData.states.forEach((state, stateData) -> { + BlueprintAnimation animation = blueprint.getAnimations().get(state); + if (animation != null) { + SimpleProperty property = new SimpleProperty(activeModel, animation, stateData.lerpIn, stateData.lerpOut, stateData.speed); + property.setPhase(stateData.phase); + property.setForceLoopMode(stateData.forceLoopMode); + property.setForceOverride(stateData.forceOverride ? BlueprintAnimation.OverrideMode.OVERRIDE : null); + activeModel.getAnimationHandler().playAnimation(property, true); + } + }); + modeledEntity.addModel(activeModel, false).ifPresent(ActiveModel::destroy); + } + } + ); + if (modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData) { + BehaviorManager manager = mountData.getMainMountManager(); + if (manager != null) { + ((MountManager)manager).setCanDrive(this.canSteer); + ((MountManager)manager).setCanRide(this.canRide); + } + } + + SavedData data = modeledEntity.save().orElse(null); + modeledEntity.destroy(); + return data; + } + + public int getRenderDistance() { + return this.renderDistance; + } + + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + public boolean isPlayerMode() { + return this.playerMode; + } + + public float getStableAngle() { + return this.stableAngle; + } + + public int getRotationDelay() { + return this.rotationDelay; + } + + public int getRotationDuration() { + return this.rotationDuration; + } + + public boolean isCanSteer() { + return this.canSteer; + } + + public boolean isCanRide() { + return this.canRide; + } + + public String getMountModelId() { + return this.mountModelId; + } + + public String getMountDriverBone() { + return this.mountDriverBone; + } + + public boolean isBaseEntityVisible() { + return this.isBaseEntityVisible; + } + + public boolean isModelRotationLock() { + return this.modelRotationLock; + } + + public Double getStepHeight() { + return this.stepHeight; + } + + public Hitbox getHitbox() { + return this.hitbox; + } + + public Map getModels() { + return this.models; + } + + public void setRenderDistance(int renderDistance) { + this.renderDistance = renderDistance; + } + + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setCanSteer(boolean canSteer) { + this.canSteer = canSteer; + } + + public void setCanRide(boolean canRide) { + this.canRide = canRide; + } + + public void setMountModelId(String mountModelId) { + this.mountModelId = mountModelId; + } + + public void setMountDriverBone(String mountDriverBone) { + this.mountDriverBone = mountDriverBone; + } + + public void setBaseEntityVisible(boolean isBaseEntityVisible) { + this.isBaseEntityVisible = isBaseEntityVisible; + } + + public void setModelRotationLock(boolean modelRotationLock) { + this.modelRotationLock = modelRotationLock; + } + + public void setStepHeight(Double stepHeight) { + this.stepHeight = stepHeight; + } + + public void setHitbox(Hitbox hitbox) { + this.hitbox = hitbox; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (!(o instanceof V3Data other)) { + return false; + } else if (!other.canEqual(this)) { + return false; + } else if (this.getRenderDistance() != other.getRenderDistance()) { + return false; + } else if (this.isHeadClampUneven() != other.isHeadClampUneven()) { + return false; + } else if (this.isBodyClampUneven() != other.isBodyClampUneven()) { + return false; + } else if (Float.compare(this.getMaxHeadAngle(), other.getMaxHeadAngle()) != 0) { + return false; + } else if (Float.compare(this.getMaxBodyAngle(), other.getMaxBodyAngle()) != 0) { + return false; + } else if (Float.compare(this.getMinHeadAngle(), other.getMinHeadAngle()) != 0) { + return false; + } else if (Float.compare(this.getMinBodyAngle(), other.getMinBodyAngle()) != 0) { + return false; + } else if (this.isPlayerMode() != other.isPlayerMode()) { + return false; + } else if (Float.compare(this.getStableAngle(), other.getStableAngle()) != 0) { + return false; + } else if (this.getRotationDelay() != other.getRotationDelay()) { + return false; + } else if (this.getRotationDuration() != other.getRotationDuration()) { + return false; + } else if (this.isCanSteer() != other.isCanSteer()) { + return false; + } else if (this.isCanRide() != other.isCanRide()) { + return false; + } else if (this.isBaseEntityVisible() != other.isBaseEntityVisible()) { + return false; + } else if (this.isModelRotationLock() != other.isModelRotationLock()) { + return false; + } else { + Object this$stepHeight = this.getStepHeight(); + Object other$stepHeight = other.getStepHeight(); + if (this$stepHeight == null ? other$stepHeight == null : this$stepHeight.equals(other$stepHeight)) { + Object this$mountModelId = this.getMountModelId(); + Object other$mountModelId = other.getMountModelId(); + if (this$mountModelId == null ? other$mountModelId == null : this$mountModelId.equals(other$mountModelId)) { + Object this$mountDriverBone = this.getMountDriverBone(); + Object other$mountDriverBone = other.getMountDriverBone(); + if (this$mountDriverBone == null ? other$mountDriverBone == null : this$mountDriverBone.equals(other$mountDriverBone)) { + Object this$hitbox = this.getHitbox(); + Object other$hitbox = other.getHitbox(); + if (this$hitbox == null ? other$hitbox == null : this$hitbox.equals(other$hitbox)) { + Object this$models = this.getModels(); + Object other$models = other.getModels(); + return this$models == null ? other$models == null : this$models.equals(other$models); + } else { + return false; + } + } else { + return false; + } + } else { + return false; + } + } else { + return false; + } + } + } + + protected boolean canEqual(Object other) { + return other instanceof V3Data; + } + + @Override + public int hashCode() { + int PRIME = 59; + int result = 1; + result = result * 59 + this.getRenderDistance(); + result = result * 59 + (this.isHeadClampUneven() ? 79 : 97); + result = result * 59 + (this.isBodyClampUneven() ? 79 : 97); + result = result * 59 + Float.floatToIntBits(this.getMaxHeadAngle()); + result = result * 59 + Float.floatToIntBits(this.getMaxBodyAngle()); + result = result * 59 + Float.floatToIntBits(this.getMinHeadAngle()); + result = result * 59 + Float.floatToIntBits(this.getMinBodyAngle()); + result = result * 59 + (this.isPlayerMode() ? 79 : 97); + result = result * 59 + Float.floatToIntBits(this.getStableAngle()); + result = result * 59 + this.getRotationDelay(); + result = result * 59 + this.getRotationDuration(); + result = result * 59 + (this.isCanSteer() ? 79 : 97); + result = result * 59 + (this.isCanRide() ? 79 : 97); + result = result * 59 + (this.isBaseEntityVisible() ? 79 : 97); + result = result * 59 + (this.isModelRotationLock() ? 79 : 97); + Object $stepHeight = this.getStepHeight(); + result = result * 59 + ($stepHeight == null ? 43 : $stepHeight.hashCode()); + Object $mountModelId = this.getMountModelId(); + result = result * 59 + ($mountModelId == null ? 43 : $mountModelId.hashCode()); + Object $mountDriverBone = this.getMountDriverBone(); + result = result * 59 + ($mountDriverBone == null ? 43 : $mountDriverBone.hashCode()); + Object $hitbox = this.getHitbox(); + result = result * 59 + ($hitbox == null ? 43 : $hitbox.hashCode()); + Object $models = this.getModels(); + return result * 59 + ($models == null ? 43 : $models.hashCode()); + } + + @Override + public String toString() { + return "V3Data(renderDistance=" + + this.getRenderDistance() + + ", isHeadClampUneven=" + + this.isHeadClampUneven() + + ", isBodyClampUneven=" + + this.isBodyClampUneven() + + ", maxHeadAngle=" + + this.getMaxHeadAngle() + + ", maxBodyAngle=" + + this.getMaxBodyAngle() + + ", minHeadAngle=" + + this.getMinHeadAngle() + + ", minBodyAngle=" + + this.getMinBodyAngle() + + ", playerMode=" + + this.isPlayerMode() + + ", stableAngle=" + + this.getStableAngle() + + ", rotationDelay=" + + this.getRotationDelay() + + ", rotationDuration=" + + this.getRotationDuration() + + ", canSteer=" + + this.isCanSteer() + + ", canRide=" + + this.isCanRide() + + ", mountModelId=" + + this.getMountModelId() + + ", mountDriverBone=" + + this.getMountDriverBone() + + ", isBaseEntityVisible=" + + this.isBaseEntityVisible() + + ", modelRotationLock=" + + this.isModelRotationLock() + + ", stepHeight=" + + this.getStepHeight() + + ", hitbox=" + + this.getHitbox() + + ", models=" + + this.getModels() + + ")"; + } + + public static class ModelData { + private final Map states = Maps.newConcurrentMap(); + private final Map defaultStates = Maps.newConcurrentMap(); + private boolean canHurt; + private boolean lockPitch; + private boolean lockYaw; + + public Map getStates() { + return this.states; + } + + public Map getDefaultStates() { + return this.defaultStates; + } + + public boolean isCanHurt() { + return this.canHurt; + } + + public boolean isLockPitch() { + return this.lockPitch; + } + + public boolean isLockYaw() { + return this.lockYaw; + } + + public void setCanHurt(boolean canHurt) { + this.canHurt = canHurt; + } + + public void setLockPitch(boolean lockPitch) { + this.lockPitch = lockPitch; + } + + public void setLockYaw(boolean lockYaw) { + this.lockYaw = lockYaw; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (!(o instanceof V3Data.ModelData other)) { + return false; + } else if (!other.canEqual(this)) { + return false; + } else if (this.isCanHurt() != other.isCanHurt()) { + return false; + } else if (this.isLockPitch() != other.isLockPitch()) { + return false; + } else if (this.isLockYaw() != other.isLockYaw()) { + return false; + } else { + Object this$states = this.getStates(); + Object other$states = other.getStates(); + if (this$states == null ? other$states == null : this$states.equals(other$states)) { + Object this$defaultStates = this.getDefaultStates(); + Object other$defaultStates = other.getDefaultStates(); + return this$defaultStates == null ? other$defaultStates == null : this$defaultStates.equals(other$defaultStates); + } else { + return false; + } + } + } + + protected boolean canEqual(Object other) { + return other instanceof V3Data.ModelData; + } + + @Override + public int hashCode() { + int PRIME = 59; + int result = 1; + result = result * 59 + (this.isCanHurt() ? 79 : 97); + result = result * 59 + (this.isLockPitch() ? 79 : 97); + result = result * 59 + (this.isLockYaw() ? 79 : 97); + Object $states = this.getStates(); + result = result * 59 + ($states == null ? 43 : $states.hashCode()); + Object $defaultStates = this.getDefaultStates(); + return result * 59 + ($defaultStates == null ? 43 : $defaultStates.hashCode()); + } + + @Override + public String toString() { + return "V3Data.ModelData(states=" + + this.getStates() + + ", defaultStates=" + + this.getDefaultStates() + + ", canHurt=" + + this.isCanHurt() + + ", lockPitch=" + + this.isLockPitch() + + ", lockYaw=" + + this.isLockYaw() + + ")"; + } + } + + public static class StateData { + private double lerpIn; + private double lerpOut; + private double time; + private double speed; + private IAnimationProperty.Phase phase; + private BlueprintAnimation.LoopMode forceLoopMode; + private boolean forceOverride; + + public double getLerpIn() { + return this.lerpIn; + } + + public double getLerpOut() { + return this.lerpOut; + } + + public double getTime() { + return this.time; + } + + public double getSpeed() { + return this.speed; + } + + public IAnimationProperty.Phase getPhase() { + return this.phase; + } + + public BlueprintAnimation.LoopMode getForceLoopMode() { + return this.forceLoopMode; + } + + public boolean isForceOverride() { + return this.forceOverride; + } + + public void setLerpIn(double lerpIn) { + this.lerpIn = lerpIn; + } + + public void setLerpOut(double lerpOut) { + this.lerpOut = lerpOut; + } + + public void setTime(double time) { + this.time = time; + } + + public void setSpeed(double speed) { + this.speed = speed; + } + + public void setPhase(IAnimationProperty.Phase phase) { + this.phase = phase; + } + + public void setForceLoopMode(BlueprintAnimation.LoopMode forceLoopMode) { + this.forceLoopMode = forceLoopMode; + } + + public void setForceOverride(boolean forceOverride) { + this.forceOverride = forceOverride; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (!(o instanceof V3Data.StateData other)) { + return false; + } else if (!other.canEqual(this)) { + return false; + } else if (Double.compare(this.getLerpIn(), other.getLerpIn()) != 0) { + return false; + } else if (Double.compare(this.getLerpOut(), other.getLerpOut()) != 0) { + return false; + } else if (Double.compare(this.getTime(), other.getTime()) != 0) { + return false; + } else if (Double.compare(this.getSpeed(), other.getSpeed()) != 0) { + return false; + } else if (this.isForceOverride() != other.isForceOverride()) { + return false; + } else { + Object this$phase = this.getPhase(); + Object other$phase = other.getPhase(); + if (this$phase == null ? other$phase == null : this$phase.equals(other$phase)) { + Object this$forceLoopMode = this.getForceLoopMode(); + Object other$forceLoopMode = other.getForceLoopMode(); + return this$forceLoopMode == null ? other$forceLoopMode == null : this$forceLoopMode.equals(other$forceLoopMode); + } else { + return false; + } + } + } + + protected boolean canEqual(Object other) { + return other instanceof V3Data.StateData; + } + + @Override + public int hashCode() { + int PRIME = 59; + int result = 1; + long $lerpIn = Double.doubleToLongBits(this.getLerpIn()); + result = result * 59 + (int)($lerpIn >>> 32 ^ $lerpIn); + long $lerpOut = Double.doubleToLongBits(this.getLerpOut()); + result = result * 59 + (int)($lerpOut >>> 32 ^ $lerpOut); + long $time = Double.doubleToLongBits(this.getTime()); + result = result * 59 + (int)($time >>> 32 ^ $time); + long $speed = Double.doubleToLongBits(this.getSpeed()); + result = result * 59 + (int)($speed >>> 32 ^ $speed); + result = result * 59 + (this.isForceOverride() ? 79 : 97); + Object $phase = this.getPhase(); + result = result * 59 + ($phase == null ? 43 : $phase.hashCode()); + Object $forceLoopMode = this.getForceLoopMode(); + return result * 59 + ($forceLoopMode == null ? 43 : $forceLoopMode.hashCode()); + } + + @Override + public String toString() { + return "V3Data.StateData(lerpIn=" + + this.getLerpIn() + + ", lerpOut=" + + this.getLerpOut() + + ", time=" + + this.getTime() + + ", speed=" + + this.getSpeed() + + ", phase=" + + this.getPhase() + + ", forceLoopMode=" + + this.getForceLoopMode() + + ", forceOverride=" + + this.isForceOverride() + + ")"; + } + } + + public static class StateProperty { + private String stateId; + private double lerpIn; + private double lerpOut; + private double speed; + + public String getStateId() { + return this.stateId; + } + + public double getLerpIn() { + return this.lerpIn; + } + + public double getLerpOut() { + return this.lerpOut; + } + + public double getSpeed() { + return this.speed; + } + + public void setStateId(String stateId) { + this.stateId = stateId; + } + + public void setLerpIn(double lerpIn) { + this.lerpIn = lerpIn; + } + + public void setLerpOut(double lerpOut) { + this.lerpOut = lerpOut; + } + + public void setSpeed(double speed) { + this.speed = speed; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (!(o instanceof V3Data.StateProperty other)) { + return false; + } else if (!other.canEqual(this)) { + return false; + } else if (Double.compare(this.getLerpIn(), other.getLerpIn()) != 0) { + return false; + } else if (Double.compare(this.getLerpOut(), other.getLerpOut()) != 0) { + return false; + } else if (Double.compare(this.getSpeed(), other.getSpeed()) != 0) { + return false; + } else { + Object this$stateId = this.getStateId(); + Object other$stateId = other.getStateId(); + return this$stateId == null ? other$stateId == null : this$stateId.equals(other$stateId); + } + } + + protected boolean canEqual(Object other) { + return other instanceof V3Data.StateProperty; + } + + @Override + public int hashCode() { + int PRIME = 59; + int result = 1; + long $lerpIn = Double.doubleToLongBits(this.getLerpIn()); + result = result * 59 + (int)($lerpIn >>> 32 ^ $lerpIn); + long $lerpOut = Double.doubleToLongBits(this.getLerpOut()); + result = result * 59 + (int)($lerpOut >>> 32 ^ $lerpOut); + long $speed = Double.doubleToLongBits(this.getSpeed()); + result = result * 59 + (int)($speed >>> 32 ^ $speed); + Object $stateId = this.getStateId(); + return result * 59 + ($stateId == null ? 43 : $stateId.hashCode()); + } + + @Override + public String toString() { + return "V3Data.StateProperty(stateId=" + + this.getStateId() + + ", lerpIn=" + + this.getLerpIn() + + ", lerpOut=" + + this.getLerpOut() + + ", speed=" + + this.getSpeed() + + ")"; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/BaseItemManager.java b/core/src/main/java/com/ticxo/modelengine/core/generator/BaseItemManager.java new file mode 100644 index 0000000..55d123c --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/BaseItemManager.java @@ -0,0 +1,271 @@ +package com.ticxo.modelengine.core.generator; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.generator.BaseItemEnum; +import com.ticxo.modelengine.api.generator.assets.ItemModel; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.utils.TFile; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.GSONUtils; +import com.ticxo.modelengine.api.utils.logger.LogColor; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.core.generator.java.BaseItem; +import com.ticxo.modelengine.core.generator.java.BaseItemTransformer; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; + +public class BaseItemManager { + private final ModelEngineAPI plugin; + private final Gson gson; + private final Map baseItems = new HashMap<>(); + private final Map requested = new LinkedHashMap<>(); + private final File baseItemFolder; + private final File itemModelFolder; + private final File cachedIDJson; + + public BaseItemManager(ModelGeneratorImpl generator) { + this.plugin = generator.getPlugin(); + this.gson = generator.getGson(); + this.baseItemFolder = TFile.createDirectory(generator.getAssetsFolder(), "minecraft", "models", "item"); + this.itemModelFolder = TFile.createDirectory(generator.getAssetsFolder(), "minecraft", "items"); + this.cachedIDJson = TFile.createFileOrEmpty(this.plugin.getDataFolder(), ".data", "cache.json"); + } + + public void updateModels() { + Set items = ConfigProperty.ITEM_MODELS.getBaseItems(); + if (items.isEmpty()) { + items.add(ConfigProperty.ITEM_MODEL.getBaseItem()); + } + + HashMap prevItems = new HashMap<>(this.baseItems); + this.baseItems.clear(); + + for (BaseItemEnum base : items) { + String name = base.name().toLowerCase(Locale.ENGLISH); + InputStream inputStream = this.plugin.getResource("pack/colorable/" + name + ".json"); + if (inputStream == null) { + TLogger.warn("Unknown colorable item: " + name + "."); + } else { + InputStreamReader itemTemplateReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); + BaseItem baseItem = (BaseItem)this.gson.fromJson(itemTemplateReader, BaseItem.class); + baseItem.setName(name); + baseItem.setBaseItemEnum(base); + this.baseItems + .computeIfAbsent( + base, + baseItemEnum -> { + BaseItemManager.BaseItemCache baseItemCache = prevItems.get(baseItemEnum); + return baseItemCache == null + ? new BaseItemManager.BaseItemCache(baseItemEnum, baseItem, new ModelIdCache()) + : baseItemCache.setBaseItem(baseItem); + } + ); + } + } + } + + public void requestId(BlueprintBone bone, Set ids) { + for (String id : ids) { + this.requested.put(id, bone); + } + } + + public void endSession() { + ModelCacheGroup group = new ModelCacheGroup(); + + for (Entry entry : this.baseItems.entrySet()) { + ModelIdCache cache = entry.getValue().getCache(); + cache.gatherExistingIds(entry.getKey(), this.requested); + group.cache.put(entry.getKey().name(), cache); + } + + for (Entry entry : this.requested.entrySet()) { + BaseItemManager.BaseItemCache cache = this.pollOptimalCache(); + cache.getCache().generateNewIds(cache.getBaseItemEnum(), entry.getKey(), entry.getValue()); + } + + for (Entry entry : this.baseItems.entrySet()) { + ModelIdCache cache = entry.getValue().getCache(); + cache.endSession(); + } + + try (FileWriter writer = new FileWriter(this.cachedIDJson)) { + writer.write(this.gson.toJson(group)); + } catch (IOException var7) { + var7.printStackTrace(); + } + } + + public void clearOverrides() { + this.baseItems.values().forEach(BaseItemManager.BaseItemCache::clearOverrides); + } + + public void registerModels(String namespace, Map aliases) { + for (Entry entry : this.baseItems.entrySet()) { + BaseItem baseItem = entry.getValue().getBaseItem(); + baseItem.addModels(namespace, entry.getValue().getCache(), aliases); + } + } + + public void createModelFiles() { + this.baseItems.values().forEach(baseItemCache -> { + BaseItem baseItem = baseItemCache.getBaseItem(); + File baseItemFile = TFile.createFile(this.baseItemFolder, baseItem.getName() + ".json"); + + try (FileWriter writer = new FileWriter(baseItemFile)) { + writer.write(this.gson.toJson(baseItem)); + } catch (IOException var14) { + var14.printStackTrace(); + } + + ItemModel ver1214 = BaseItemTransformer.to1214Format(baseItem); + File ver1214File = TFile.createFile(this.itemModelFolder, baseItem.getName() + ".json"); + + try (FileWriter writer = new FileWriter(ver1214File)) { + writer.write(this.gson.toJson(BaseItemTransformer.wrapModel(this.gson, ver1214, true))); + } catch (IOException var11) { + var11.printStackTrace(); + } + }); + } + + public void refreshCache() { + TFile.recreateFile(this.cachedIDJson); + + try (FileReader reader = new FileReader(this.cachedIDJson)) { + ModelCacheGroup cacheGroup = null; + JsonObject generic = (JsonObject)this.gson.fromJson(reader, JsonObject.class); + if (generic != null) { + String version = GSONUtils.get(generic, "version", JsonElement::getAsString, "R4.0.0"); + if (!generic.has("version") && !generic.has("cachedId")) { + version = "B4.0.8"; + } + + TLogger.log(LogColor.BRIGHT_GREEN + "Loading cache version: " + version); + switch (version) { + case "R4.0.0": + BaseItemEnum item = ConfigProperty.ITEM_MODEL.getBaseItem(); + ModelIdCache cache = (ModelIdCache)this.gson.fromJson(generic, ModelIdCache.class); + cacheGroup = new ModelCacheGroup(); + cacheGroup.cache.put(item.name(), cache); + break; + case "B4.0.8": + JsonObject root = new JsonObject(); + root.addProperty("version", "R4.0.8"); + root.add("cache", generic); + cacheGroup = (ModelCacheGroup)this.gson.fromJson(root, ModelCacheGroup.class); + break; + case "R4.0.8": + cacheGroup = (ModelCacheGroup)this.gson.fromJson(generic, ModelCacheGroup.class); + } + } + + if (cacheGroup == null) { + TLogger.warn("Unable to read the model ID cache file. If the file is missing, ignore this warning."); + cacheGroup = new ModelCacheGroup(); + + for (BaseItemEnum baseItem : ConfigProperty.ITEM_MODELS.getBaseItems()) { + cacheGroup.cache.put(baseItem.name(), new ModelIdCache()); + } + } + + Set items = ConfigProperty.ITEM_MODELS.getBaseItems(); + if (items.isEmpty()) { + items.add(ConfigProperty.ITEM_MODEL.getBaseItem()); + } + + for (Entry entry : cacheGroup.cache.entrySet()) { + BaseItemEnum item = BaseItemEnum.get(entry.getKey()); + if (item != null && items.contains(item)) { + this.baseItems + .compute( + item, + (baseItemEnum, baseItemCache) -> baseItemCache == null + ? new BaseItemManager.BaseItemCache(baseItemEnum, new BaseItem(), entry.getValue()) + : baseItemCache.setCache(entry.getValue()) + ); + } + } + } catch (IOException var11) { + TLogger.error("Unable to read the model ID cache file. Is it corrupted?"); + var11.printStackTrace(); + } + } + + public void cleanUp() { + this.baseItems.values().forEach(baseItemCache -> baseItemCache.getCache().cleanUp()); + } + + private BaseItemManager.BaseItemCache pollOptimalCache() { + int load = Integer.MAX_VALUE; + BaseItemManager.BaseItemCache cache = null; + + for (BaseItemManager.BaseItemCache baseItemCache : this.baseItems.values()) { + int l = baseItemCache.getCache().getCacheLoad(); + if (l < load) { + load = l; + cache = baseItemCache; + } + } + + if (cache == null) { + throw new RuntimeException("No cache is available!"); + } else { + return cache; + } + } + + private static class BaseItemCache { + private BaseItemEnum baseItemEnum; + private BaseItem baseItem; + private ModelIdCache cache; + + public BaseItem getBaseItem() { + return this.baseItem; + } + + public BaseItemManager.BaseItemCache setBaseItem(BaseItem baseItem) { + this.baseItem = baseItem; + return this; + } + + public ModelIdCache getCache() { + return this.cache; + } + + public BaseItemManager.BaseItemCache setCache(ModelIdCache cache) { + this.cache = cache; + return this; + } + + public void clearOverrides() { + if (this.baseItem != null) { + this.baseItem.clearOverrides(); + } + } + + public BaseItemCache(BaseItemEnum baseItemEnum, BaseItem baseItem, ModelIdCache cache) { + this.baseItemEnum = baseItemEnum; + this.baseItem = baseItem; + this.cache = cache; + } + + public BaseItemEnum getBaseItemEnum() { + return this.baseItemEnum; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/ModelCacheGroup.java b/core/src/main/java/com/ticxo/modelengine/core/generator/ModelCacheGroup.java new file mode 100644 index 0000000..fe94272 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/ModelCacheGroup.java @@ -0,0 +1,9 @@ +package com.ticxo.modelengine.core.generator; + +import java.util.HashMap; +import java.util.Map; + +public class ModelCacheGroup { + protected final String version = "R4.0.8"; + protected final Map cache = new HashMap<>(); +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/ModelGeneratorImpl.java b/core/src/main/java/com/ticxo/modelengine/core/generator/ModelGeneratorImpl.java new file mode 100644 index 0000000..00d046e --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/ModelGeneratorImpl.java @@ -0,0 +1,820 @@ +package com.ticxo.modelengine.core.generator; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Ordering; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.error.ErrorCollector; +import com.ticxo.modelengine.api.error.IError; +import com.ticxo.modelengine.api.events.ModelRegistrationEvent; +import com.ticxo.modelengine.api.events.RegisterParserEvent; +import com.ticxo.modelengine.api.generator.ModelGenerator; +import com.ticxo.modelengine.api.generator.assets.BlueprintTexture; +import com.ticxo.modelengine.api.generator.assets.ItemModel; +import com.ticxo.modelengine.api.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.generator.assets.JavaItemModel; +import com.ticxo.modelengine.api.generator.assets.ModelAssets; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.generator.parser.ModelParser; +import com.ticxo.modelengine.api.model.ModelRegistry; +import com.ticxo.modelengine.api.utils.MiscUtils; +import com.ticxo.modelengine.api.utils.TFile; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.ResourceLocation; +import com.ticxo.modelengine.api.utils.logger.LogColor; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.ticker.DualTicker; +import com.ticxo.modelengine.core.generator.atlas.AtlasManager; +import com.ticxo.modelengine.core.generator.java.BaseItemTransformer; +import com.ticxo.modelengine.core.generator.parser.blockbench.BlockbenchParser; +import com.ticxo.modelengine.core.javasupport.Java21Access; +import it.unimi.dsi.fastutil.Pair; +import java.awt.image.BufferedImage; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.Map.Entry; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.zip.ZipOutputStream; +import javax.imageio.ImageIO; +import org.bukkit.Bukkit; +import org.bukkit.NamespacedKey; + +public class ModelGeneratorImpl implements ModelGenerator { + private static final List OVERLAYS = List.of("1_19_4", "1_21_2", "1_21_4", "1_21_5", "1_21_6", "26_1", "26_2"); + private final ModelEngineAPI plugin; + private final Gson gson; + private final List parsers = new ArrayList<>(); + private final List assets = new ArrayList<>(); + private final AtlasManager atlasManager; + private final BaseItemManager baseItemManager; + private final ExecutorService generatorService = Executors.newFixedThreadPool( + ConfigProperty.MAX_GENERATOR_THREADS.getIntOrIfNeg(() -> Runtime.getRuntime().availableProcessors()) + ); + private final File blueprintFolder; + private final File internalFolder; + private final File internalExampleFolder; + private final File internalBlueprintFolder; + private final File packFolder; + private final File assetsFolder; + private final File zippedResourcePack; + private final Map> tasks = Maps.newConcurrentMap(); + private final Set executed = new HashSet<>(); + private String namespace; + private String texturePath; + private File modelFolder; + private File itemsFolder; + private boolean generateMeta; + private boolean deleteOld; + private boolean mergeItemModels; + private Set disabledOverlays = Set.of(); + private boolean initialized; + private final long[] timer = new long[3]; + private final Map textureNameCache = new HashMap<>(); + private final Set writtenTextures = ConcurrentHashMap.newKeySet(); + private final Map modelAliases = new ConcurrentHashMap<>(); + + public ModelGeneratorImpl(ModelEngineAPI plugin) { + this.plugin = plugin; + this.gson = plugin.getGson(); + this.blueprintFolder = TFile.createDirectory(plugin.getDataFolder(), "blueprints"); + this.internalFolder = TFile.createDirectory(plugin.getDataFolder(), "internals"); + this.internalExampleFolder = TFile.createDirectory(this.internalFolder, "examples"); + this.internalBlueprintFolder = TFile.createDirectory(this.internalFolder, "blueprints"); + this.packFolder = TFile.createDirectory(plugin.getDataFolder(), "resource pack"); + this.assetsFolder = TFile.createDirectory(this.packFolder, "assets"); + this.zippedResourcePack = TFile.createFile(plugin.getDataFolder(), "resource pack.zip"); + this.atlasManager = new AtlasManager(this); + this.baseItemManager = new BaseItemManager(this); + this.baseItemManager.refreshCache(); + plugin.getConfigManager().registerReferenceUpdate(this::updateConfig); + this.parsers.add(new BlockbenchParser(this)); + ModelEngineAPI.callEvent(new RegisterParserEvent(this.parsers)); + } + + @Override + public void importModels(boolean isStartup) { + this.executed.clear(); + this.queueTask(ModelGenerator.Phase.PRE_IMPORT, () -> this.timer[0] = System.nanoTime()); + this.queueTask(ModelGenerator.Phase.POST_IMPORT, () -> this.timer[0] = System.nanoTime() - this.timer[0]); + this.queueTask(ModelGenerator.Phase.PRE_ASSETS, () -> this.timer[1] = System.nanoTime()); + this.queueTask(ModelGenerator.Phase.POST_ASSETS, () -> this.timer[1] = System.nanoTime() - this.timer[1]); + this.queueTask(ModelGenerator.Phase.PRE_ZIPPING, () -> this.timer[2] = System.nanoTime()); + this.queueTask(ModelGenerator.Phase.POST_ZIPPING, () -> this.timer[2] = System.nanoTime() - this.timer[2]); + this.queueTask(ModelGenerator.Phase.FINISHED, () -> { + TLogger.log(LogColor.BRIGHT_GREEN + "Generator Profiled:"); + TLogger.log(LogColor.BRIGHT_GREEN + " - Import Phase: " + MiscUtils.FORMATTER.format(this.timer[0] / 1000000.0) + "ms"); + TLogger.log(LogColor.BRIGHT_GREEN + " - Assets Phase: " + MiscUtils.FORMATTER.format(this.timer[1] / 1000000.0) + "ms"); + TLogger.log(LogColor.BRIGHT_GREEN + " - Zipping Phase: " + MiscUtils.FORMATTER.format(this.timer[2] / 1000000.0) + "ms"); + }); + if (isStartup && !ConfigProperty.LATE_REGISTER.getBoolean()) { + this.importModelsInternal(true); + } else { + DualTicker.queueAsyncTask(() -> CompletableFuture.runAsync(() -> this.importModelsInternal(isStartup))); + } + } + + @Override + public void generateAssets(boolean isStartup) { + if (!ConfigProperty.LATE_REGISTER.getBoolean() && ConfigProperty.LATE_ASSETS.getBoolean()) { + DualTicker.queueAsyncTask(() -> CompletableFuture.runAsync(() -> this.generateAssetsInternal(isStartup))); + } else { + this.generateAssetsInternal(true); + } + } + + @Override + public void zipResourcePack(boolean isStartup) { + if (!ConfigProperty.ZIP.getBoolean()) { + this.executeQueuedTask(ModelGenerator.Phase.FINISHED); + } else { + if (!ConfigProperty.LATE_ASSETS.getBoolean() && ConfigProperty.LATE_ZIPPING.getBoolean()) { + DualTicker.queueAsyncTask(() -> CompletableFuture.runAsync(this::zipResourcePackInternal)); + } else { + this.zipResourcePackInternal(); + } + } + } + + @Override + public void updateConfig() { + this.namespace = ConfigProperty.NAMESPACE.getString().toLowerCase(Locale.ENGLISH); + this.texturePath = ConfigProperty.TEXTURE_PATH.getString().toLowerCase(Locale.ENGLISH); + this.modelFolder = TFile.createDirectory(this.assetsFolder, this.namespace, "models"); + this.itemsFolder = TFile.createDirectory(this.assetsFolder, this.namespace, "items"); + this.baseItemManager.updateModels(); + this.generateMeta = ConfigProperty.MCMETA.getBoolean(); + this.deleteOld = ConfigProperty.DELETE_OLD.getBoolean(); + this.mergeItemModels = ConfigProperty.MERGE_ITEM_MODELS.getBoolean(); + this.disabledOverlays = new HashSet<>(); + List raw = ConfigProperty.DISABLED_OVERLAYS.getStringList(); + ArrayList resolved = new ArrayList<>(); + + for (Object entry : raw) { + String text = String.valueOf(entry).trim(); + String version = OVERLAYS.stream().filter(overlay -> overlay.equals(text) || digitsOf(overlay).equals(digitsOf(text))).findFirst().orElse(null); + if (version == null) { + TLogger.warn("Unknown entry in Disabled-Overlays: " + text + ". Valid overlays: " + OVERLAYS); + } else { + this.disabledOverlays.add(version); + resolved.add(version); + } + } + + if (!raw.equals(resolved)) { + this.plugin.getConfigManager().set(ConfigProperty.DISABLED_OVERLAYS, resolved); + this.plugin.getConfigManager().save(); + } + } + + @Override + public void queueTask(ModelGenerator.Phase post, Runnable task) { + if (!this.executed.contains(ModelGenerator.Phase.FINISHED) && !this.executed.contains(post)) { + this.tasks.computeIfAbsent(post, phase -> new LinkedHashSet<>()).add(task); + } else { + task.run(); + } + } + + private void executeQueuedTask(ModelGenerator.Phase phase) { + this.executed.add(phase); + if (phase == ModelGenerator.Phase.FINISHED) { + this.tasks.values().forEach(runnables -> runnables.forEach(Runnable::run)); + this.tasks.clear(); + } else { + this.tasks.computeIfPresent(phase, (p, runnables) -> { + runnables.forEach(Runnable::run); + runnables.clear(); + return runnables; + }); + } + + ModelEngineAPI.callEvent(new ModelRegistrationEvent(phase)); + } + + private void importModelsInternal(boolean isStartup) { + TLogger.log(); + TLogger.log(LogColor.BOLD + LogColor.CYAN.toString() + "[Importing models]"); + this.initialized = false; + this.executeQueuedTask(ModelGenerator.Phase.PRE_IMPORT); + this.baseItemManager.refreshCache(); + this.textureNameCache.clear(); + ModelRegistry registry = this.plugin.getModelRegistry(); + registry.clearRegistry(); + this.copyInternalFiles(); + List files = Lists.newArrayList(); + File[] fa = this.blueprintFolder.listFiles(); + if (fa != null) { + files.addAll(Arrays.asList(fa)); + } + + fa = this.internalBlueprintFolder.listFiles(); + if (fa != null) { + files.addAll(Arrays.asList(fa)); + } + + if (Bukkit.getPluginManager().getPlugin("MythicMobs") != null) { + try { + files.addAll(Java21Access.getMythicPackModelFiles.call()); + } catch (Throwable var9) { + var9.printStackTrace(); + } + } + + if (files.isEmpty()) { + this.initialized = true; + this.executeQueuedTask(ModelGenerator.Phase.FINISHED); + } else { + Queue compartment = new LinkedList<>(); + files.sort(Ordering.natural()); + ArrayList> importTasks = new ArrayList<>(); + + label54: + while (true) { + for (File file : files) { + if (!file.isFile()) { + if (file.isDirectory()) { + compartment.add(file); + } + } else { + importTasks.add( + CompletableFuture.runAsync( + () -> { + boolean fileParsed = false; + ErrorCollector collector = new ErrorCollector(file.getName()); + + for (ModelParser parser : this.parsers) { + if (parser.validateFile(file)) { + try { + Pair modelData = parser.generate(file, collector); + if (modelData != null) { + ModelBlueprint blueprint = (ModelBlueprint)modelData.left(); + ModelAssets asset = (ModelAssets)modelData.right(); + blueprint.finalizeModel(collector); + + for (Entry boneEntry : blueprint.getFlatMap().entrySet()) { + BlueprintBone bone = boneEntry.getValue(); + if (bone.isRenderer()) { + synchronized (this.baseItemManager) { + this.baseItemManager.requestId(bone, bone.getModelData().getMultiModels().getKeys()); + } + + if (this.mergeItemModels) { + bone.getModelData() + .setSingleComposite( + new ItemModelData.SingleComposite(new NamespacedKey(this.namespace, blueprint.getName())) + ); + bone.getModelData().setVariant(bone.getName()); + } else { + bone.getModelData() + .setSingleComposite( + new ItemModelData.SingleComposite( + new NamespacedKey(this.namespace, blueprint.getName() + "/" + bone.getName()) + ) + ); + } + } + } + + synchronized (registry) { + registry.registerBlueprint(blueprint); + } + + synchronized (this.assets) { + this.assets.add(asset); + } + + fileParsed = true; + break; + } + + if (collector.hasError()) { + collector.logAll(); + } + } catch (Exception var22) { + var22.printStackTrace(); + break; + } + } + } + + if (!fileParsed) { + IError.UNKNOWN_FORMAT.log(collector); + } + + synchronized (this.timer) { + collector.logAll(); + } + }, + this.generatorService + ) + .handle((res, ex) -> { + if (ex != null) { + ex.printStackTrace(); + } + + return null; + }) + ); + } + } + + while (!compartment.isEmpty()) { + File[] ca = compartment.poll().listFiles(); + if (ca != null && ca.length != 0) { + files = Arrays.asList(ca); + continue label54; + } + } + + CompletableFuture.allOf(importTasks.toArray(CompletableFuture[]::new)).thenRunAsync(() -> { + this.initialized = true; + this.baseItemManager.endSession(); + this.executeQueuedTask(ModelGenerator.Phase.POST_IMPORT); + this.generateAssets(isStartup); + }).handle((res, ex) -> { + if (ex != null) { + ex.printStackTrace(); + } + + return null; + }); + return; + } + } + } + + private void generateAssetsInternal(boolean isStartup) { + this.executeQueuedTask(ModelGenerator.Phase.PRE_ASSETS); + this.baseItemManager.clearOverrides(); + this.atlasManager.reset(); + this.writtenTextures.clear(); + this.modelAliases.clear(); + if (this.deleteOld && !TFile.delete(this.packFolder)) { + TLogger.error("Failed to clear old resource pack folder."); + } + + ArrayList> assetTasks = new ArrayList<>(); + + for (ModelAssets asset : this.assets) { + assetTasks.add( + CompletableFuture.runAsync( + () -> { + for (BlueprintTexture texture : asset.getTextures()) { + if (!"minecraft".equals(texture.getPath().getNamespace())) { + this.atlasManager.addSingle(texture.getPath()); + if (this.writtenTextures.add(texture.getPath())) { + File png = TFile.createFile(this.assetsFolder, "textures", texture.getPath(), "png"); + BufferedImage image = TFile.toImage(texture.getSource()); + + try { + byte[] palette = PaletteImageWriter.encode(image); + if (palette != null) { + Files.write(png.toPath(), palette); + } else { + ImageIO.write(image, "png", png); + } + } catch (IOException var24) { + var24.printStackTrace(); + } + + if (texture.getMcMeta() != null && this.shouldGenerateMCMeta(image, texture)) { + HashMap lazyMCMeta = new HashMap<>(); + File mcmeta = TFile.createFile(this.assetsFolder, "textures", texture.getPath(), "png.mcmeta"); + + try (FileWriter writer = new FileWriter(mcmeta)) { + lazyMCMeta.put("animation", texture.getMcMeta()); + writer.write(this.gson.toJson(lazyMCMeta)); + } catch (IOException var23) { + var23.printStackTrace(); + } + } + } + } + } + + ItemModel.Select select = this.mergeItemModels ? new ItemModel.Select() : null; + HashMap writtenModels = new HashMap<>(); + + for (Collection models : asset.getModels().values()) { + if (models.size() == 1) { + JavaItemModel model = models.iterator().next(); + String json = this.gson.toJson(model); + String canonical = writtenModels.putIfAbsent(json, model.getName()); + if (canonical == null) { + canonical = model.getName(); + File modelJson = TFile.createFile(this.modelFolder, asset.getName(), model.getName() + ".json"); + + try (FileWriter writer = new FileWriter(modelJson)) { + writer.write(json); + } catch (IOException var20) { + var20.printStackTrace(); + } + } else { + this.modelAliases.put(asset.getName() + "/" + model.getName(), asset.getName() + "/" + canonical); + } + + this.writeItemModel( + asset, model.getName(), new ItemModel.Model(new NamespacedKey(this.namespace, asset.getName() + "/" + canonical)), select + ); + } else { + int id = 0; + String modelName = ""; + ItemModel.Composite composite = new ItemModel.Composite(); + + for (JavaItemModel model : models) { + model.finalizeModel(); + File modelJson; + if (id == 0) { + modelName = model.getName(); + modelJson = TFile.createFile(this.modelFolder, asset.getName(), model.getName() + ".json"); + composite.getModels().add(new ItemModel.Model(new NamespacedKey(this.namespace, asset.getName() + "/" + model.getName()))); + } else { + modelJson = TFile.createFile(this.modelFolder, asset.getName(), model.getName(), id + ".json"); + composite.getModels() + .add(new ItemModel.Model(new NamespacedKey(this.namespace, asset.getName() + "/" + model.getName() + "/" + id))); + } + + id++; + + try (FileWriter writer = new FileWriter(modelJson)) { + writer.write(this.gson.toJson(model)); + } catch (IOException var17) { + var17.printStackTrace(); + } + } + + this.writeItemModel(asset, modelName, composite, select); + } + } + + if (select != null && !select.getCases().isEmpty()) { + select.setFallback(select.getCases().get(0).model()); + this.writeItemJson(TFile.createFile(this.itemsFolder, asset.getName() + ".json"), select, asset); + } + }, + this.generatorService + ) + .handleAsync((res, ex) -> { + if (ex != null) { + ex.printStackTrace(); + } + + return null; + }, this.generatorService) + ); + } + + CompletableFuture.allOf(assetTasks.toArray(CompletableFuture[]::new)).thenRunAsync(() -> { + this.assets.clear(); + this.baseItemManager.registerModels(this.namespace, this.modelAliases); + this.baseItemManager.createModelFiles(); + this.baseItemManager.cleanUp(); + if (ConfigProperty.ATLAS.getBoolean()) { + this.atlasManager.generateFile(); + } + + this.copyResources(); + this.executeQueuedTask(ModelGenerator.Phase.POST_ASSETS); + this.zipResourcePack(isStartup); + }, this.generatorService).handleAsync((res, ex) -> { + if (ex != null) { + ex.printStackTrace(); + } + + return null; + }, this.generatorService); + } + + private void writeItemModel(ModelAssets asset, String boneName, ItemModel itemModel, ItemModel.Select select) { + if (select != null) { + select.getCases().add(new ItemModel.Select.Case(itemModel, boneName)); + } else { + this.writeItemJson(TFile.createFile(this.itemsFolder, asset.getName(), boneName + ".json"), itemModel, asset); + } + } + + private void writeItemJson(File itemJson, ItemModel itemModel, ModelAssets asset) { + try (FileWriter writer = new FileWriter(itemJson)) { + writer.write(this.gson.toJson(BaseItemTransformer.wrapModel(this.gson, itemModel, asset.getName().equals("head")))); + } catch (IOException var9) { + var9.printStackTrace(); + } + } + + private void copyInternalFiles() { + TFile.copyResource(this.plugin, TFile.createFile(this.internalExampleFolder, "player_model.bbmodel"), "internal/player_model.bbmodel"); + TFile.copyResource(this.plugin, TFile.createFile(this.internalBlueprintFolder, "internal_fire.bbmodel"), "internal/internal_fire.bbmodel"); + } + + private void copyResources() { + TFile.copyResource(this.plugin, this.packFolder, "pack", "pack.png"); + if (this.disabledOverlays.isEmpty()) { + HashMap overlayReplacements = new HashMap<>(); + + for (String version : OVERLAYS) { + overlayReplacements.put("modelengine_" + version, this.namespace + "_" + version); + } + + TFile.copyResourceTemplated(this.plugin, this.packFolder, "pack", "pack.mcmeta", "pack.mcmeta", overlayReplacements); + } else { + this.copyFilteredPackMeta(); + } + + if (ConfigProperty.SHADER.getBoolean()) { + Map namespaceReplacements = Map.of("modelengine:", this.namespace + ":"); + TFile.copyResourceTemplated( + this.plugin, + this.packFolder, + "pack", + "assets/modelengine/items/player_head.json", + "assets/" + this.namespace + "/items/player_head.json", + namespaceReplacements + ); + if (this.isOverlayEnabled("1_21_4")) { + TFile.copyResourceTemplated( + this.plugin, + this.packFolder, + "pack", + "modelengine_1_21_4/assets/modelengine/items/player_head.json", + this.namespace + "_1_21_4/assets/" + this.namespace + "/items/player_head.json", + namespaceReplacements + ); + } + + for (String limb : List.of("head", "left_arm", "left_leg", "right_arm", "right_leg", "slim_left", "slim_right", "torso")) { + TFile.copyResource( + this.plugin, + this.packFolder, + "pack", + "assets/modelengine/models/custom/entities/player/" + limb + ".json", + "assets/" + this.namespace + "/models/custom/entities/player/" + limb + ".json" + ); + } + + if (this.isOverlayEnabled("1_19_4")) { + TFile.copyResourceTemplated( + this.plugin, + this.packFolder, + "pack", + "modelengine_1_19_4/assets/minecraft/models/item/player_head.json", + this.namespace + "_1_19_4/assets/minecraft/models/item/player_head.json", + namespaceReplacements + ); + } + + this.copyOverlayResource("1_21_2", "assets/minecraft/shaders/core/rendertype_entity_translucent.fsh"); + this.copyOverlayResource("1_21_2", "assets/minecraft/shaders/core/rendertype_entity_translucent.json"); + this.copyOverlayResource("1_21_2", "assets/minecraft/shaders/core/rendertype_entity_translucent.vsh"); + this.copyOverlayResource("1_21_2", "assets/minecraft/shaders/core/entity.fsh"); + this.copyOverlayResource("1_21_2", "assets/minecraft/shaders/core/entity.vsh"); + this.copyOverlayResource("1_21_5", "assets/minecraft/shaders/core/entity.fsh"); + this.copyOverlayResource("1_21_5", "assets/minecraft/shaders/core/entity.vsh"); + this.copyOverlayResource("1_21_6", "assets/minecraft/shaders/core/entity.fsh"); + this.copyOverlayResource("1_21_6", "assets/minecraft/shaders/core/entity.vsh"); + this.copyOverlayResource("26_1", "assets/minecraft/shaders/core/entity.fsh"); + this.copyOverlayResource("26_1", "assets/minecraft/shaders/core/entity.vsh"); + this.copyOverlayResource("26_2", "assets/minecraft/shaders/core/entity.fsh"); + this.copyOverlayResource("26_2", "assets/minecraft/shaders/core/entity.vsh"); + TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/core/entity.fsh"); + TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/core/entity.vsh"); + TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/core/rendertype_entity_translucent.fsh"); + TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/core/rendertype_entity_translucent.json"); + TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/core/rendertype_entity_translucent.vsh"); + TFile.copyResource(this.plugin, this.packFolder, "pack", "assets/minecraft/shaders/include/player_shader.glsl"); + } + } + + private void copyOverlayResource(String version, String relativePath) { + if (this.isOverlayEnabled(version)) { + TFile.copyResource( + this.plugin, this.packFolder, "pack", "modelengine_" + version + "/" + relativePath, this.namespace + "_" + version + "/" + relativePath + ); + } + } + + private static String digitsOf(String value) { + return value.replaceAll("[^0-9]", ""); + } + + private boolean isOverlayEnabled(String version) { + return !this.disabledOverlays.contains(version); + } + + private void copyFilteredPackMeta() { + File file = TFile.createFile(this.packFolder, "pack.mcmeta"); + if (!file.exists()) { + try { + try (InputStream reader = this.plugin.getResource("pack/pack.mcmeta")) { + if (reader != null) { + JsonObject root = (JsonObject)this.gson.fromJson(new String(reader.readAllBytes(), StandardCharsets.UTF_8), JsonObject.class); + JsonObject overlays = root.getAsJsonObject("overlays"); + if (overlays != null) { + JsonArray kept = new JsonArray(); + + for (JsonElement element : overlays.getAsJsonArray("entries")) { + JsonObject entry = element.getAsJsonObject(); + String version = entry.get("directory").getAsString().substring("modelengine_".length()); + if (this.isOverlayEnabled(version)) { + entry.addProperty("directory", this.namespace + "_" + version); + kept.add(entry); + } + } + + overlays.add("entries", kept); + } + + Files.writeString(file.toPath(), this.gson.toJson(root), StandardCharsets.UTF_8); + return; + } + } + } catch (IOException var12) { + var12.printStackTrace(); + } + } + } + + private void zipResourcePackInternal() { + this.executeQueuedTask(ModelGenerator.Phase.PRE_ZIPPING); + + try { + ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(this.zippedResourcePack), 65536)); + File[] files = this.packFolder.listFiles(); + if (files == null) { + zipOut.close(); + this.executeQueuedTask(ModelGenerator.Phase.FINISHED); + return; + } + + Arrays.sort((Object[])files); + + for (File file : files) { + TFile.zipFile(file, file.getName(), zipOut, false); + } + + zipOut.close(); + TLogger.log(); + TLogger.log(LogColor.BRIGHT_GREEN + "Resource pack zipped."); + } catch (IOException var7) { + var7.printStackTrace(); + } + + this.executeQueuedTask(ModelGenerator.Phase.POST_ZIPPING); + this.executeQueuedTask(ModelGenerator.Phase.FINISHED); + } + + private boolean shouldGenerateMCMeta(BufferedImage image, BlueprintTexture texture) { + if (texture.getMcMeta().isMustGenerate()) { + return true; + } else if (!this.generateMeta) { + return false; + } else { + float textureRatio = (float)image.getHeight() / image.getWidth(); + float uvRatio = (float)texture.getFrameHeight() / texture.getFrameWidth(); + return TMath.isSimilar(textureRatio, uvRatio) ? false : textureRatio / uvRatio > 1.0F; + } + } + + public ModelEngineAPI getPlugin() { + return this.plugin; + } + + public Gson getGson() { + return this.gson; + } + + public List getParsers() { + return this.parsers; + } + + public List getAssets() { + return this.assets; + } + + public AtlasManager getAtlasManager() { + return this.atlasManager; + } + + public BaseItemManager getBaseItemManager() { + return this.baseItemManager; + } + + public ExecutorService getGeneratorService() { + return this.generatorService; + } + + public File getBlueprintFolder() { + return this.blueprintFolder; + } + + public File getInternalFolder() { + return this.internalFolder; + } + + public File getInternalExampleFolder() { + return this.internalExampleFolder; + } + + public File getInternalBlueprintFolder() { + return this.internalBlueprintFolder; + } + + public File getPackFolder() { + return this.packFolder; + } + + public File getAssetsFolder() { + return this.assetsFolder; + } + + public File getZippedResourcePack() { + return this.zippedResourcePack; + } + + public Map> getTasks() { + return this.tasks; + } + + public Set getExecuted() { + return this.executed; + } + + public String getNamespace() { + return this.namespace; + } + + public String getTexturePath() { + return this.texturePath; + } + + public File getModelFolder() { + return this.modelFolder; + } + + public File getItemsFolder() { + return this.itemsFolder; + } + + public boolean isGenerateMeta() { + return this.generateMeta; + } + + public boolean isDeleteOld() { + return this.deleteOld; + } + + public boolean isMergeItemModels() { + return this.mergeItemModels; + } + + public Set getDisabledOverlays() { + return this.disabledOverlays; + } + + @Override + public boolean isInitialized() { + return this.initialized; + } + + public long[] getTimer() { + return this.timer; + } + + public Map getTextureNameCache() { + return this.textureNameCache; + } + + public Set getWrittenTextures() { + return this.writtenTextures; + } + + public Map getModelAliases() { + return this.modelAliases; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/ModelIdCache.java b/core/src/main/java/com/ticxo/modelengine/core/generator/ModelIdCache.java new file mode 100644 index 0000000..85c8f15 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/ModelIdCache.java @@ -0,0 +1,86 @@ +package com.ticxo.modelengine.core.generator; + +import com.ticxo.modelengine.api.generator.BaseItemEnum; +import com.ticxo.modelengine.api.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.Map.Entry; +import java.util.function.BiConsumer; + +public class ModelIdCache { + protected final Map cachedId = new HashMap<>(); + protected final Queue unused = new LinkedList<>(); + private final transient Map dataToModel = new HashMap<>(); + private final transient Set pendingRemove = new HashSet<>(); + protected int nextId = 1; + private transient int maxId; + + public void gatherExistingIds(BaseItemEnum baseItem, Map requested) { + this.maxId = 0; + this.dataToModel.clear(); + + for (Entry entry : this.cachedId.entrySet()) { + String modelId = entry.getKey(); + Integer dataId = entry.getValue(); + if (requested.containsKey(modelId)) { + BlueprintBone bone = requested.remove(modelId); + bone.setDataId(dataId); + bone.setBaseItem(baseItem); + ItemModelData.SubModel submodel = bone.getModelData().getMultiModels().getSubModel(modelId); + submodel.setData(dataId); + submodel.setItem(baseItem); + this.dataToModel.put(dataId, modelId); + this.maxId = Math.max(dataId, this.maxId); + } else { + this.pendingRemove.add(modelId); + this.unused.add(this.cachedId.get(modelId)); + } + } + + this.pendingRemove.forEach(this.cachedId::remove); + this.pendingRemove.clear(); + } + + public void generateNewIds(BaseItemEnum baseItem, String modelId, BlueprintBone bone) { + int id = this.unused.isEmpty() ? this.nextId++ : this.unused.poll(); + bone.setDataId(id); + bone.setBaseItem(baseItem); + ItemModelData.SubModel submodel = bone.getModelData().getMultiModels().getSubModel(modelId); + submodel.setData(id); + submodel.setItem(baseItem); + this.maxId = Math.max(id, this.maxId); + this.dataToModel.put(id, modelId); + this.cachedId.put(modelId, id); + } + + public void endSession() { + for (int id : this.unused) { + this.maxId = Math.max(this.maxId, id); + } + + this.nextId = this.maxId + 1; + } + + public void sortedIterate(BiConsumer consumer) { + for (int i = 1; i < this.nextId; i++) { + String id = this.dataToModel.get(i); + if (id != null) { + consumer.accept(id.replace(":", "/"), i); + } + } + } + + public void cleanUp() { + this.dataToModel.clear(); + this.pendingRemove.clear(); + } + + public int getCacheLoad() { + return this.cachedId.size(); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/PaletteImageWriter.java b/core/src/main/java/com/ticxo/modelengine/core/generator/PaletteImageWriter.java new file mode 100644 index 0000000..b09c975 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/PaletteImageWriter.java @@ -0,0 +1,194 @@ +package com.ticxo.modelengine.core.generator; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import java.util.zip.CRC32; +import java.util.zip.Deflater; + +final class PaletteImageWriter { + private static final byte[] SIGNATURE = new byte[]{-119, 80, 78, 71, 13, 10, 26, 10}; + private static final int MAX_PALETTE = 256; + private static final byte COLOR_TYPE_INDEXED = 3; + private static final byte FILTER_NONE = 0; + + private PaletteImageWriter() { + } + + static byte[] encode(BufferedImage image) throws IOException { + if (image == null) { + return null; + } else { + int width = image.getWidth(); + int height = image.getHeight(); + if (width > 0 && height > 0) { + int[] pixels = image.getRGB(0, 0, width, height, null, 0, width); + HashMap distinct = new HashMap<>(); + + for (int pixel : pixels) { + if (distinct.size() > 256) { + return null; + } + + distinct.putIfAbsent(pixel, 0); + } + + if (distinct.size() > 256) { + return null; + } else { + int[] palette = distinct.keySet().stream().sorted((a, b) -> { + int alpha = Integer.compare(a >>> 24, b >>> 24); + return alpha != 0 ? alpha : Integer.compare(a & 16777215, b & 16777215); + }).mapToInt(Integer::intValue).toArray(); + + for (int i = 0; i < palette.length; i++) { + distinct.put(palette[i], i); + } + + int bitDepth = bitDepth(palette.length); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(SIGNATURE); + writeChunk(out, "IHDR", header(width, height, bitDepth)); + writeChunk(out, "PLTE", palette(palette)); + int translucent = countTranslucent(palette); + if (translucent > 0) { + writeChunk(out, "tRNS", transparency(palette, translucent)); + } + + writeChunk(out, "IDAT", deflate(scanlines(pixels, distinct, width, height, bitDepth))); + writeChunk(out, "IEND", new byte[0]); + return out.toByteArray(); + } + } else { + return null; + } + } + } + + private static int bitDepth(int colors) { + if (colors <= 2) { + return 1; + } else if (colors <= 4) { + return 2; + } else { + return colors <= 16 ? 4 : 8; + } + } + + private static int countTranslucent(int[] palette) { + int count = 0; + + for (int i = 0; i < palette.length; i++) { + if (palette[i] >>> 24 != 255) { + count = i + 1; + } + } + + return count; + } + + private static byte[] header(int width, int height, int bitDepth) { + byte[] data = new byte[13]; + writeInt(data, 0, width); + writeInt(data, 4, height); + data[8] = (byte)bitDepth; + data[9] = 3; + return data; + } + + private static byte[] palette(int[] palette) { + byte[] data = new byte[palette.length * 3]; + + for (int i = 0; i < palette.length; i++) { + data[i * 3] = (byte)(palette[i] >>> 16); + data[i * 3 + 1] = (byte)(palette[i] >>> 8); + data[i * 3 + 2] = (byte)palette[i]; + } + + return data; + } + + private static byte[] transparency(int[] palette, int count) { + byte[] data = new byte[count]; + + for (int i = 0; i < count; i++) { + data[i] = (byte)(palette[i] >>> 24); + } + + return data; + } + + private static byte[] scanlines(int[] pixels, Map indices, int width, int height, int bitDepth) { + int perByte = 8 / bitDepth; + int rowBytes = (width + perByte - 1) / perByte; + byte[] raw = new byte[(rowBytes + 1) * height]; + int at = 0; + + for (int y = 0; y < height; y++) { + raw[at++] = 0; + int row = y * width; + + for (int x = 0; x < width; x++) { + int index = indices.get(pixels[row + x]); + if (bitDepth == 8) { + raw[at + x] = (byte)index; + } else { + int shift = 8 - bitDepth * (x % perByte + 1); + raw[at + x / perByte] = (byte)(raw[at + x / perByte] | (byte)(index << shift)); + } + } + + at += rowBytes; + } + + return raw; + } + + private static byte[] deflate(byte[] raw) { + Deflater deflater = new Deflater(9); + + byte[] var8; + try { + deflater.setInput(raw); + deflater.finish(); + ByteArrayOutputStream out = new ByteArrayOutputStream(raw.length / 2 + 64); + byte[] buffer = new byte[8192]; + + while (!deflater.finished()) { + int read = deflater.deflate(buffer); + out.write(buffer, 0, read); + } + + var8 = out.toByteArray(); + } finally { + deflater.end(); + } + + return var8; + } + + private static void writeChunk(ByteArrayOutputStream out, String type, byte[] data) throws IOException { + byte[] header = new byte[4]; + writeInt(header, 0, data.length); + out.write(header); + byte[] name = type.getBytes(StandardCharsets.US_ASCII); + out.write(name); + out.write(data); + CRC32 crc = new CRC32(); + crc.update(name); + crc.update(data); + byte[] trailer = new byte[4]; + writeInt(trailer, 0, (int)crc.getValue()); + out.write(trailer); + } + + private static void writeInt(byte[] target, int offset, int value) { + target[offset] = (byte)(value >>> 24); + target[offset + 1] = (byte)(value >>> 16); + target[offset + 2] = (byte)(value >>> 8); + target[offset + 3] = (byte)value; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/atlas/Atlas.java b/core/src/main/java/com/ticxo/modelengine/core/generator/atlas/Atlas.java new file mode 100644 index 0000000..1755a67 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/atlas/Atlas.java @@ -0,0 +1,52 @@ +package com.ticxo.modelengine.core.generator.atlas; + +import com.ticxo.modelengine.api.utils.data.ResourceLocation; +import java.util.ArrayList; +import java.util.List; + +public class Atlas { + private final List sources = new ArrayList<>(); + + public List getSources() { + return this.sources; + } + + public static class Directory extends Atlas.Source { + public final String source; + public final String prefix; + + public Directory(String location) { + super("directory"); + this.source = location; + this.prefix = location + "/"; + } + } + + public static class Filter extends Atlas.Source { + public final ResourceLocation pattern; + + public Filter(ResourceLocation pattern) { + super("filter"); + this.pattern = pattern; + } + } + + public static class Single extends Atlas.Source { + public final String resource; + public final String sprite; + + public Single(String location) { + super("single"); + this.resource = location; + this.sprite = location; + } + } + + public static class Source { + public final String type; + + public Source(String type) { + this.type = type; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/atlas/AtlasManager.java b/core/src/main/java/com/ticxo/modelengine/core/generator/atlas/AtlasManager.java new file mode 100644 index 0000000..60fc4ff --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/atlas/AtlasManager.java @@ -0,0 +1,66 @@ +package com.ticxo.modelengine.core.generator.atlas; + +import com.ticxo.modelengine.api.utils.TFile; +import com.ticxo.modelengine.api.utils.data.ResourceLocation; +import com.ticxo.modelengine.core.generator.ModelGeneratorImpl; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Set; + +public class AtlasManager { + private final ModelGeneratorImpl generator; + private final File atlases; + private final Set registeredPaths = new HashSet<>(); + private final Atlas atlas; + + public AtlasManager(ModelGeneratorImpl generator) { + this.generator = generator; + this.atlases = TFile.createDirectory(generator.getPackFolder(), "assets", "minecraft", "atlases"); + this.atlas = new Atlas(); + this.reset(); + } + + public void reset() { + this.registeredPaths.clear(); + this.atlas.getSources().clear(); + this.atlas.getSources().add(new Atlas.Directory(this.generator.getTexturePath())); + this.atlas.getSources().add(new Atlas.Filter(new ResourceLocation("minecraft", "entity/fishing_hook"))); + } + + public synchronized int addSingle(ResourceLocation location) { + String path = location.getPath(); + if (path.startsWith("entity") || path.startsWith("item") || path.startsWith("block")) { + return 2; + } else if (!this.registeredPaths.add(location)) { + return 1; + } else { + this.atlas.getSources().add(new Atlas.Single(location.toString())); + return 0; + } + } + + public void generateFile() { + this.atlas + .getSources() + .sort( + Comparator.comparingInt(s -> s instanceof Atlas.Single ? 1 : 0) + .thenComparing(s -> s instanceof Atlas.Single ? ((Atlas.Single)s).resource : "") + ); + + try { + File file = TFile.createFile(this.atlases, "blocks.json"); + FileWriter writer = new FileWriter(file); + writer.write(this.generator.getGson().toJson(this.atlas)); + writer.close(); + } catch (IOException var3) { + var3.printStackTrace(); + } + } + + public Atlas getAtlas() { + return this.atlas; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/java/BaseItem.java b/core/src/main/java/com/ticxo/modelengine/core/generator/java/BaseItem.java new file mode 100644 index 0000000..45e368c --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/java/BaseItem.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.core.generator.java; + +import com.ticxo.modelengine.api.generator.BaseItemEnum; +import com.ticxo.modelengine.core.generator.ModelIdCache; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class BaseItem { + private final List overrides = new ArrayList<>(); + private transient String name; + private transient BaseItemEnum baseItemEnum; + private String parent; + private Map textures; + + public void clearOverrides() { + this.overrides.clear(); + } + + public void addModels(String namespace, ModelIdCache cache, Map aliases) { + cache.sortedIterate((model, id) -> this.overrides.add(new BaseItem.JavaOverride(namespace + ":" + aliases.getOrDefault(model, model), id))); + } + + public List getOverrides() { + return this.overrides; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public BaseItemEnum getBaseItemEnum() { + return this.baseItemEnum; + } + + public void setBaseItemEnum(BaseItemEnum baseItemEnum) { + this.baseItemEnum = baseItemEnum; + } + + static class JavaOverride { + private final BaseItem.JavaPredicate predicate; + private final String model; + + public JavaOverride(String model, int id) { + this.model = model; + this.predicate = new BaseItem.JavaPredicate(id); + } + + public BaseItem.JavaPredicate getPredicate() { + return this.predicate; + } + + public String getModel() { + return this.model; + } + } + + record JavaPredicate(int custom_model_data) { + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/java/BaseItemTransformer.java b/core/src/main/java/com/ticxo/modelengine/core/generator/java/BaseItemTransformer.java new file mode 100644 index 0000000..0151357 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/java/BaseItemTransformer.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.core.generator.java; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.ticxo.modelengine.api.generator.assets.ItemModel; +import com.ticxo.modelengine.api.generator.assets.TintSource; + +public class BaseItemTransformer { + public static ItemModel to1214Format(BaseItem item) { + ItemModel.RangeDispatch model = new ItemModel.RangeDispatch(); + + TintSource tint = (TintSource)(switch (item.getBaseItemEnum()) { + case FILLED_MAP -> new TintSource.MapColor(-1); + case LEATHER_BOOTS, LEATHER_CHESTPLATE, LEATHER_HORSE_ARMOR, LEATHER_LEGGINGS -> new TintSource.Dye(-1); + case LINGERING_POTION, POTION, SPLASH_POTION, TIPPED_ARROW -> new TintSource.Potion(-1); + }); + + for (BaseItem.JavaOverride overrides : item.getOverrides()) { + int id = overrides.getPredicate().custom_model_data(); + ItemModel.Model idModel = new ItemModel.Model(overrides.getModel()); + idModel.getTints().add(tint); + model.getEntries().add(new ItemModel.RangeDispatch.Entry(idModel, id)); + } + + ItemModel.Model fallback = new ItemModel.Model("minecraft:item/" + item.getName()); + switch (item.getBaseItemEnum()) { + case FILLED_MAP: + fallback.getTints().add(new TintSource.Constant(-1)); + fallback.getTints().add(new TintSource.MapColor()); + break; + case LEATHER_BOOTS: + case LEATHER_CHESTPLATE: + case LEATHER_HORSE_ARMOR: + case LEATHER_LEGGINGS: + fallback.getTints().add(new TintSource.Dye()); + break; + case LINGERING_POTION: + case POTION: + case SPLASH_POTION: + case TIPPED_ARROW: + fallback.getTints().add(new TintSource.Potion()); + } + + model.setFallback(fallback); + return model; + } + + public static JsonElement wrapModel(Gson gson, ItemModel model, boolean oversized) { + JsonObject obj = new JsonObject(); + obj.add("model", gson.toJsonTree(model)); + if (oversized) { + obj.add("oversized_in_gui", new JsonPrimitive(true)); + } + + return obj; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/BlockbenchParser.java b/core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/BlockbenchParser.java new file mode 100644 index 0000000..f02560a --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/BlockbenchParser.java @@ -0,0 +1,583 @@ +package com.ticxo.modelengine.core.generator.parser.blockbench; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.BlueprintAnimation; +import com.ticxo.modelengine.api.animation.Timeline; +import com.ticxo.modelengine.api.animation.keyframe.KeyframeType; +import com.ticxo.modelengine.api.animation.keyframe.KeyframeTypes; +import com.ticxo.modelengine.api.animation.keyframe.data.KeyframeReaderRegistry; +import com.ticxo.modelengine.api.animation.keyframe.type.ScriptKeyframe; +import com.ticxo.modelengine.api.animation.keyframe.type.VectorKeyframe; +import com.ticxo.modelengine.api.error.ErrorCollector; +import com.ticxo.modelengine.api.error.IError; +import com.ticxo.modelengine.api.error.WarnBadTexture; +import com.ticxo.modelengine.api.error.WarnDuplicateTexture; +import com.ticxo.modelengine.api.error.WarningDuplicateBoneName; +import com.ticxo.modelengine.api.events.RegisterBehaviorParserEvent; +import com.ticxo.modelengine.api.generator.assets.BlueprintTexture; +import com.ticxo.modelengine.api.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.generator.assets.JavaItemModel; +import com.ticxo.modelengine.api.generator.assets.ModelAssets; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.generator.parser.ModelParser; +import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchBehaviorParser; +import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchDeserializer; +import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchModel; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.utils.MiscUtils; +import com.ticxo.modelengine.api.utils.TFile; +import com.ticxo.modelengine.api.utils.data.ResourceLocation; +import com.ticxo.modelengine.api.utils.math.Direction; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.core.generator.ModelGeneratorImpl; +import com.ticxo.modelengine.core.generator.parser.blockbench.json.DefaultBehaviorParser; +import com.ticxo.modelengine.core.generator.parser.blockbench.json.MCMetaDeserializer; +import com.ticxo.modelengine.core.generator.processed.ProcessedBone; +import it.unimi.dsi.fastutil.Pair; +import java.io.File; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.zip.CRC32; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3d; +import org.joml.Vector3f; + +public class BlockbenchParser implements ModelParser { + private final Gson gson = new GsonBuilder() + .registerTypeAdapter(BlockbenchModel.class, new BlockbenchDeserializer()) + .registerTypeAdapter(BlueprintTexture.MCMeta.class, new MCMetaDeserializer()) + .create(); + private final Set behaviorParsers = new LinkedHashSet<>(); + private final ModelGeneratorImpl generator; + private final ConcurrentHashMap bbmodelCache = new ConcurrentHashMap<>(); + + public BlockbenchParser(ModelGeneratorImpl generator) { + this.generator = generator; + this.behaviorParsers.add(new DefaultBehaviorParser()); + ModelEngineAPI.callEvent(new RegisterBehaviorParserEvent(this.behaviorParsers)); + } + + @Override + public boolean validateFile(File file) { + return TFile.isExtension(file.getName(), "bbmodel"); + } + + @Override + public Pair generate(File file, ErrorCollector collector) throws Exception { + String modelName = TFile.removeExtension(file.getName()).toLowerCase(Locale.ENGLISH); + + try { + String cacheKey = file.getAbsolutePath(); + long lastModified = file.lastModified(); + long size = file.length(); + BlockbenchParser.CachedBBFile cached = this.bbmodelCache.get(cacheKey); + String json; + if (cached != null && cached.lastModified == lastModified && cached.size == size) { + json = cached.json; + } else { + byte[] bytes = Files.readAllBytes(file.toPath()); + CRC32 crc = new CRC32(); + crc.update(bytes); + long hash = crc.getValue(); + json = new String(bytes); + if (cached != null && cached.hash == hash) { + this.bbmodelCache.put(cacheKey, new BlockbenchParser.CachedBBFile(lastModified, size, cached.hash, cached.json)); + } else { + this.bbmodelCache.put(cacheKey, new BlockbenchParser.CachedBBFile(lastModified, size, hash, json)); + } + } + + BlockbenchModel blockbenchModel = (BlockbenchModel)this.gson.fromJson(json, BlockbenchModel.class); + ModelBlueprint blueprint = new ModelBlueprint(); + blueprint.setName(modelName); + this.populateBlueprint(blockbenchModel, blueprint, collector); + blueprint.constructFlatBoneMap(collector); + blueprint.cacheBoneBehaviors(collector); + ModelAssets assets = new ModelAssets(); + assets.setName(modelName); + this.populateAssets(blockbenchModel, blueprint, assets, collector); + return Pair.of(blueprint, assets); + } catch (Exception var15) { + final Exception e = var15; + collector.collect(new IError() { + @Override + public String getErrorMessage() { + return "Error: " + e.getMessage(); + } + + @Override + public IError.Severity getSeverity() { + return IError.Severity.ERROR; + } + }); + return null; + } + } + + private void populateBlueprint(BlockbenchModel bbmodel, ModelBlueprint blueprint, ErrorCollector collector) { + this.behaviorParsers.forEach(parser -> parser.processModel(collector, bbmodel, blueprint)); + HashMap uuidToBone = new HashMap<>(); + bbmodel.getOutliner().forEach((uuidx, group) -> { + BlueprintBone bone = this.readBone(collector, bbmodel, null, group, uuidToBone); + if (blueprint.getBones().containsKey(bone.getName())) { + new WarningDuplicateBoneName(bone.getName(), bone.getUuid()).log(collector); + bone.setName(uuidx.toString()); + } + + blueprint.getBones().put(bone.getName(), bone); + uuidToBone.put(bone.getUuid(), bone); + }); + + for (Entry entry : bbmodel.getAnimations().entrySet()) { + String name = entry.getKey().toLowerCase(Locale.ENGLISH); + BlockbenchModel.Animation value = entry.getValue(); + BlueprintAnimation blueprintAnimation = new BlueprintAnimation(blueprint, name); + if (value.getEffects() != null) { + Map> effectChannels = value.getEffects().getChannels(); + Map script = effectChannels.get("timeline"); + if (script != null) { + for (Entry scriptEntry : script.entrySet()) { + BlockbenchModel.Keyframe bbFrame = scriptEntry.getValue(); + ScriptKeyframe frame = blueprintAnimation.getGlobalTimeline().getKeyframe(scriptEntry.getKey(), KeyframeTypes.SCRIPT); + + for (Map data : bbFrame.getData_points()) { + String instructions = data.getOrDefault("script", ""); + + for (String instruction : instructions.split("\n")) { + frame.getScript().add(ScriptKeyframe.Script.from(instruction)); + } + } + } + } + } + + for (Entry timelineEntry : value.getAnimators().entrySet()) { + BlockbenchModel.Animator animator = timelineEntry.getValue(); + if (!animator.getChannels().isEmpty()) { + boolean hasKeyframes = false; + Timeline timeline = new Timeline(blueprintAnimation, animator.getRotation_global() != null && animator.getRotation_global()); + hasKeyframes |= putVectorKeyframes(animator, "position", timeline, KeyframeTypes.POSITION, 0.0625F, 0.0625F, -0.0625F); + hasKeyframes |= putVectorKeyframes( + animator, "rotation", timeline, KeyframeTypes.ROTATION, (float) (Math.PI / 180.0), (float) (-Math.PI / 180.0), (float) (-Math.PI / 180.0) + ); + hasKeyframes |= putVectorKeyframes(animator, "scale", timeline, KeyframeTypes.SCALE, 1.0F, 1.0F, 1.0F); + if (hasKeyframes) { + UUID uuid = animator.getUuid(); + if (uuid != null) { + blueprintAnimation.getTimelines().put(uuid, timeline); + } + } + } + } + + blueprintAnimation.setLength(value.getLength().floatValue()); + blueprintAnimation.setLoopMode(BlueprintAnimation.LoopMode.get(value.getLoop())); + blueprintAnimation.setOverride(value.getOverride()); + blueprint.getAnimations().put(name, blueprintAnimation); + } + + String[] lines = bbmodel.getAnimation_variable_placeholders().split("\n"); + + for (String line : lines) { + String[] pair = line.split("=", 2); + if (pair.length >= 2) { + blueprint.getAnimationsPlaceholders().put(pair[0], pair[1]); + } + } + } + + private BlueprintBone readBone( + ErrorCollector collector, BlockbenchModel model, @Nullable BlueprintBone parent, BlockbenchModel.Group group, Map uuidToBone + ) { + BlueprintBone blueprintBone = new BlueprintBone(); + blueprintBone.setName(group.getName().toLowerCase(Locale.ENGLISH)); + blueprintBone.setUuid(group.getUuid()); + blueprintBone.setGlobalPosition(vector3f(group.getOrigin()).mul(-0.0625F, 0.0625F, -0.0625F)); + Vector3f rotation = vector3f(group.getRotation()).mul((float) (-Math.PI / 180.0), (float) (Math.PI / 180.0), (float) (-Math.PI / 180.0)); + blueprintBone.setLocalRotation(rotation); + blueprintBone.getLocalQuaternion().rotateZYX(rotation.z, rotation.y, rotation.x); + if (parent != null) { + blueprintBone.setLocalPosition(blueprintBone.getGlobalPosition().sub(parent.getGlobalPosition(), new Vector3f())); + Quaternionf boneQuaternion = new Quaternionf().rotationZYX(rotation.z, rotation.y, rotation.x); + Quaternionf parentQuaternion = parent.getGlobalQuaternion(); + parentQuaternion.mul(boneQuaternion, boneQuaternion); + Vector3f global = TMath.getEulerAnglesZYX(boneQuaternion, new Vector3f()); + blueprintBone.setGlobalRotation(new Vector3f(global.x, global.y, global.z)); + blueprintBone.setGlobalQuaternion(boneQuaternion); + Vector3f rotatedLocal = blueprintBone.getLocalPosition().rotate(parentQuaternion, new Vector3f()); + blueprintBone.setRotatedGlobalPosition(rotatedLocal.add(parent.getRotatedGlobalPosition())); + } else { + blueprintBone.setLocalPosition(new Vector3f(blueprintBone.getGlobalPosition())); + blueprintBone.setGlobalRotation(rotation); + blueprintBone.setGlobalQuaternion(new Quaternionf(blueprintBone.getLocalQuaternion())); + blueprintBone.setRotatedGlobalPosition(new Vector3f(blueprintBone.getGlobalPosition())); + } + + blueprintBone.setParent(parent); + this.behaviorParsers.forEach(parser -> parser.processBone(collector, model, group, blueprintBone)); + + for (Entry entry : group.getChildGroup().entrySet()) { + BlueprintBone child = this.readBone(collector, model, blueprintBone, entry.getValue(), uuidToBone); + if (blueprintBone.getChildren().containsKey(child.getName())) { + new WarningDuplicateBoneName(child.getName(), child.getUuid()).log(collector); + child.setName(child.getUuid().toString()); + } + + blueprintBone.getChildren().put(child.getName(), child); + } + + for (UUID element : group.getElement()) { + if (model.getElements().get(element) instanceof BlockbenchModel.AnimatableElement animatable) { + BlueprintBone child = this.readElementAsBone(blueprintBone, animatable, uuidToBone); + if (blueprintBone.getChildren().containsKey(child.getName())) { + new WarningDuplicateBoneName(child.getName(), child.getUuid()).log(collector); + child.setName(child.getUuid().toString()); + } + + blueprintBone.getChildren().put(child.getName(), child); + } + } + + uuidToBone.put(blueprintBone.getUuid(), blueprintBone); + return blueprintBone; + } + + private BlueprintBone readElementAsBone(@Nullable BlueprintBone parent, BlockbenchModel.AnimatableElement element, Map uuidToBone) { + BlueprintBone blueprintBone = new BlueprintBone(); + blueprintBone.setName(element.getName().toLowerCase(Locale.ENGLISH)); + blueprintBone.setUuid(element.getUuid()); + blueprintBone.setGlobalPosition(vector3f(element.getOrigin()).mul(-0.0625F, 0.0625F, -0.0625F)); + Vector3f rotation = vector3f(element.getRotation()).mul((float) (-Math.PI / 180.0), (float) (Math.PI / 180.0), (float) (-Math.PI / 180.0)); + blueprintBone.setLocalRotation(rotation); + blueprintBone.getLocalQuaternion().rotateZYX(rotation.z, rotation.y, rotation.x); + if (parent != null) { + blueprintBone.setLocalPosition(blueprintBone.getGlobalPosition().sub(parent.getGlobalPosition(), new Vector3f())); + Quaternionf boneQuaternion = new Quaternionf().rotationZYX(rotation.z, rotation.y, rotation.x); + Quaternionf parentQuaternion = parent.getGlobalQuaternion(); + parentQuaternion.mul(boneQuaternion, boneQuaternion); + Vector3f global = TMath.getEulerAnglesZYX(boneQuaternion, new Vector3f()); + blueprintBone.setGlobalRotation(new Vector3f(global.x, global.y, global.z)); + blueprintBone.setGlobalQuaternion(boneQuaternion); + Vector3f rotatedLocal = blueprintBone.getLocalPosition().rotate(parentQuaternion, new Vector3f()); + blueprintBone.setRotatedGlobalPosition(rotatedLocal.add(parent.getRotatedGlobalPosition())); + } else { + blueprintBone.setLocalPosition(new Vector3f(blueprintBone.getGlobalPosition())); + blueprintBone.setGlobalRotation(rotation); + blueprintBone.setGlobalQuaternion(new Quaternionf(blueprintBone.getLocalQuaternion())); + blueprintBone.setRotatedGlobalPosition(new Vector3f(blueprintBone.getGlobalPosition())); + } + + blueprintBone.setParent(parent); + uuidToBone.put(blueprintBone.getUuid(), blueprintBone); + return blueprintBone; + } + + private void populateAssets(BlockbenchModel bbmodel, ModelBlueprint blueprint, ModelAssets assets, ErrorCollector collector) { + this.populateTexture(bbmodel, blueprint, assets, collector); + this.populateModel(bbmodel, blueprint, assets, collector); + } + + private void populateTexture(BlockbenchModel bbmodel, ModelBlueprint blueprint, ModelAssets assets, ErrorCollector collector) { + Map textures = bbmodel.getTextures(); + + for (Entry entry : textures.entrySet()) { + Integer id = entry.getKey(); + BlockbenchModel.Texture bbTexture = entry.getValue(); + BlueprintTexture.MCMeta meta; + if (bbTexture.getRaw_mcmeta() == null) { + meta = new BlueprintTexture.MCMeta(); + meta.setFrametime(bbTexture.getFrame_time()); + meta.setInterpolate(MiscUtils.orDef(false, bbTexture.getFrame_interpolate()) ? true : null); + if (bbTexture.getFrame_order() != null && !bbTexture.getFrame_order().isBlank()) { + for (String frame : bbTexture.getFrame_order().split(" ")) { + meta.addFrame(TMath.tryParse(frame, 0)); + } + } + } else { + meta = (BlueprintTexture.MCMeta)this.gson.fromJson(bbTexture.getRaw_mcmeta(), BlueprintTexture.MCMeta.class); + meta.setMustGenerate(true); + } + + BlueprintTexture texture = this.constructBlueprintTexture(id, bbmodel, bbTexture, meta, blueprint, collector); + assets.getTextures().add(texture); + } + } + + @NotNull + private BlueprintTexture constructBlueprintTexture( + Integer id, BlockbenchModel bbmodel, BlockbenchModel.Texture bbTexture, BlueprintTexture.MCMeta meta, ModelBlueprint blueprint, ErrorCollector collector + ) { + BlueprintTexture texture = new BlueprintTexture(); + texture.setId(id); + texture.setFrameWidth(MiscUtils.or(bbTexture.getUv_width(), bbmodel.getResolution().getWidth())); + texture.setFrameHeight(MiscUtils.or(bbTexture.getUv_height(), bbmodel.getResolution().getHeight())); + String namespace = bbTexture.getNamespace().isBlank() ? this.generator.getNamespace() : bbTexture.getNamespace(); + String folder = !namespace.equals(this.generator.getNamespace()) && !bbTexture.getFolder().isBlank() + ? bbTexture.getFolder().toLowerCase(Locale.ENGLISH) + : this.generator.getTexturePath(); + String name = TFile.removeExtension(bbTexture.getName()).toLowerCase(Locale.ENGLISH); + ResourceLocation location = new ResourceLocation(namespace, folder + "/" + name); + if (!location.isValid()) { + ResourceLocation correct = new ResourceLocation( + this.generator.getNamespace(), this.generator.getTexturePath() + "/" + MiscUtils.generateUUIDFromString(name) + ); + new WarnBadTexture(location, correct).log(collector); + location = correct; + } + + Map cache = this.generator.getTextureNameCache(); + if (Optional.ofNullable(cache.get(location.toString())).map(string -> !string.equals(bbTexture.getSource())).orElse(false)) { + ResourceLocation correct = new ResourceLocation( + this.generator.getNamespace(), this.generator.getTexturePath() + "/" + MiscUtils.generateUUIDFromString(blueprint.getName() + ":" + name) + ); + new WarnDuplicateTexture(location, correct).log(collector); + location = correct; + } + + this.generator.getTextureNameCache().put(location.toString(), bbTexture.getSource()); + texture.setPath(location); + texture.setMcMeta(meta); + texture.setSource(bbTexture.getSource()); + return texture; + } + + private void populateModel(BlockbenchModel bbmodel, ModelBlueprint blueprint, ModelAssets assets, ErrorCollector collector) { + label67: + for (Entry entry : blueprint.getFlatMap().entrySet()) { + String name = entry.getKey(); + BlueprintBone bone = entry.getValue(); + BlockbenchModel.Group bbBone = bbmodel.getGroup(bone.getUuid()); + if (bbBone != null && bbBone.isExport()) { + for (BoneBehaviorType behaviorType : bone.getCachedBehaviorProvider().keySet()) { + if (behaviorType.isIgnoreCubes()) { + continue label67; + } + } + + Set javaModels = null; + int scale = 1; + if (ModelEngineAPI.getConfigCache().isUseNewRotation()) { + JavaItemModel model = this.createItemModel(bbmodel, bone, bbBone, assets); + if (model != null) { + javaModels = Set.of(model); + scale = model.scaleToFit(); + } + } else { + ProcessedBone processedBone = this.process(bbmodel, bone, bbBone, assets, collector); + javaModels = processedBone.getModels(); + scale = processedBone.getScale(); + } + + if (javaModels != null && !javaModels.isEmpty()) { + bone.setRenderer(true); + bone.setScale(scale); + ItemModelData.MultiModels multiModel = bone.getModelData().getMultiModels(); + + for (int i = 0; i < javaModels.size(); i++) { + multiModel.addSubModel(new ItemModelData.SubModel(blueprint.getName() + ":" + (i == 0 ? bone.getName() : bone.getName() + "/" + i))); + } + + assets.getModels().put(name, javaModels); + } + } + } + } + + private JavaItemModel createItemModel(BlockbenchModel model, BlueprintBone blueprintBone, BlockbenchModel.Group group, ModelAssets assets) { + JavaItemModel javaItemModel = new JavaItemModel(); + javaItemModel.setName(blueprintBone.getName()); + boolean isRenderer = false; + + for (UUID elementId : group.getElement()) { + BlockbenchModel.Element bbElement = model.getElements().get(elementId); + if (bbElement instanceof BlockbenchModel.Cube cube) { + JavaItemModel.JavaElement element = new JavaItemModel.JavaElement(); + float[] boneOrigin = unwrap(group.getOrigin(), 3); + float[] cubeOrigin = unwrap(cube.getOrigin(), 3); + float[] from = unwrap(cube.getFrom(), 3); + float[] to = unwrap(cube.getTo(), 3); + element.from(boneOrigin, from, cube.getInflate()); + element.to(boneOrigin, to, cube.getInflate()); + JavaItemModel.JavaElement.RotationFree free = new JavaItemModel.JavaElement.RotationFree(); + free.origin(boneOrigin, cubeOrigin); + free.rotation(unwrap(cube.getRotation(), 3)); + element.setRotation(free); + + for (Entry faceEntry : cube.getFaces().entrySet()) { + String dir = faceEntry.getKey(); + BlockbenchModel.Face bbFace = faceEntry.getValue(); + if (!bbFace.isEmpty()) { + int id = bbFace.getTexture(); + if (assets.getTextures().size() > id) { + BlockbenchModel.Texture tex = model.getTextures().get(id); + JavaItemModel.JavaElement.Face face = new JavaItemModel.JavaElement.Face(); + face.setRotation(bbFace.getRotation()); + face.uv( + MiscUtils.or(tex.getUv_width(), model.getResolution().getWidth()), + MiscUtils.or(tex.getUv_height(), model.getResolution().getHeight()), + unwrap(bbFace.getUv(), 4) + ); + face.setTexture("#" + id); + element.getFaces().put(dir, face); + Map textures = javaItemModel.getTextures(); + textures.computeIfAbsent(String.valueOf(id), s -> assets.getTextures().get(id).getPath().toString()); + if (textures.size() == 1) { + textures.computeIfAbsent("particle", s -> "#" + id); + } + } + } + } + + if (!element.getFaces().isEmpty()) { + isRenderer = true; + javaItemModel.addElement(element); + } + + if (cube.isTranslucent()) { + blueprintBone.getModelData().setTranslucent(true); + } + } + } + + return isRenderer ? javaItemModel : null; + } + + private ProcessedBone process(BlockbenchModel model, BlueprintBone blueprintBone, BlockbenchModel.Group group, ModelAssets assets, ErrorCollector collector) { + ProcessedBone bone = new ProcessedBone(blueprintBone.getName(), vector3f(group.getOrigin()), vector3f(group.getRotation())); + + for (UUID uuid : group.getElement()) { + if (model.getElements().get(uuid) instanceof BlockbenchModel.Cube cube) { + Map faces = new HashMap<>(); + + for (Entry faceEntry : cube.getFaces().entrySet()) { + BlockbenchModel.Face face = faceEntry.getValue(); + if (!face.isEmpty()) { + Float[] faceUV = face.getUv(); + ProcessedBone.UV uv = new ProcessedBone.UV( + faceUV[0] == null ? 0.0F : faceUV[0], + faceUV[1] == null ? 0.0F : faceUV[1], + faceUV[2] == null ? 0.0F : faceUV[2], + faceUV[3] == null ? 0.0F : faceUV[3], + face.getRotation() == null ? 0 : face.getRotation() + ); + ProcessedBone.Face procFace = new ProcessedBone.Face(uv, face.getTexture()); + faces.put(Direction.valueOf(faceEntry.getKey().toUpperCase(Locale.ENGLISH)), procFace); + } + } + + if (!faces.isEmpty()) { + ProcessedBone.Cube procCube = new ProcessedBone.Cube( + cube.getName(), + vector3d(cube.getOrigin()).sub(bone.getBoneOrigin()), + vector3d(cube.getRotation()), + vector3d(cube.getFrom()).sub(bone.getBoneOrigin()), + vector3d(cube.getTo()).sub(bone.getBoneOrigin()), + faces, + cube.getInflate() == null ? 0.0F : cube.getInflate() + ); + bone.getCubes().add(procCube); + if (cube.isTranslucent()) { + blueprintBone.getModelData().setTranslucent(true); + } + } + } + } + + bone.splitModels(model, assets); + return bone; + } + + private static Vector3f vector3f(@Nullable Float[] vec) { + return vec == null ? new Vector3f() : new Vector3f(vec[0] == null ? 0.0F : vec[0], vec[1] == null ? 0.0F : vec[1], vec[2] == null ? 0.0F : vec[2]); + } + + private static Vector3d vector3d(@Nullable Float[] vec) { + return vec == null + ? new Vector3d() + : new Vector3d(vec[0] == null ? 0.0 : vec[0].floatValue(), vec[1] == null ? 0.0 : vec[1].floatValue(), vec[2] == null ? 0.0 : vec[2].floatValue()); + } + + private static float[] unwrap(Float[] arr, int length) { + if (arr == null) { + return new float[length]; + } else { + float[] a = new float[arr.length]; + + for (int i = 0; i < arr.length; i++) { + if (arr[i] != null) { + a[i] = arr[i]; + } + } + + return a; + } + } + + private static boolean putVectorKeyframes( + BlockbenchModel.Animator animator, + String channel, + Timeline timeline, + KeyframeType keyframeType, + float scaleX, + float scaleY, + float scaleZ + ) { + Map frames = animator.getChannels().get(channel); + if (frames != null && !frames.isEmpty()) { + for (Entry entry : frames.entrySet()) { + Float time = entry.getKey(); + BlockbenchModel.Keyframe keyframe = entry.getValue(); + VectorKeyframe vectorKeyframe = timeline.getKeyframe(time, keyframeType); + if (!keyframe.getData_points().isEmpty()) { + KeyframeReaderRegistry reader = ModelEngineAPI.getAPI().getKeyframeReaderRegistry(); + Map pre = keyframe.getData_points().get(0); + vectorKeyframe.setXFactor(scaleX) + .setYFactor(scaleY) + .setZFactor(scaleZ) + .setX(reader.tryParse(pre.getOrDefault("x", "0"))) + .setY(reader.tryParse(pre.getOrDefault("y", "0"))) + .setZ(reader.tryParse(pre.getOrDefault("z", "0"))); + if (keyframe.getData_points().size() >= 2) { + Map post = keyframe.getData_points().get(1); + vectorKeyframe.setDiscontinuous(true); + vectorKeyframe.setPostX(reader.tryParse(post.getOrDefault("x", "0"))) + .setPostY(reader.tryParse(post.getOrDefault("y", "0"))) + .setPostZ(reader.tryParse(post.getOrDefault("z", "0"))); + } + } + + vectorKeyframe.setInterpolation(keyframe.getInterpolation()); + if (vectorKeyframe.isBezier()) { + float[] leftTime = unwrap(keyframe.getBezier_left_time(), 3); + float[] leftValue = unwrap(keyframe.getBezier_left_value(), 3); + float[] rightTime = unwrap(keyframe.getBezier_right_time(), 3); + float[] rightValue = unwrap(keyframe.getBezier_right_value(), 3); + vectorKeyframe.setBezierLeftTime(leftTime[0], leftTime[1], leftTime[2]); + vectorKeyframe.setBezierLeftValue(leftValue[0], leftValue[1], leftValue[2]); + vectorKeyframe.setBezierRightTime(rightTime[0], rightTime[1], rightTime[2]); + vectorKeyframe.setBezierRightValue(rightValue[0], rightValue[1], rightValue[2]); + } + } + + return true; + } else { + return false; + } + } + + private record CachedBBFile(long lastModified, long size, long hash, String json) { + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/json/DefaultBehaviorParser.java b/core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/json/DefaultBehaviorParser.java new file mode 100644 index 0000000..0cba432 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/json/DefaultBehaviorParser.java @@ -0,0 +1,371 @@ +package com.ticxo.modelengine.core.generator.parser.blockbench.json; + +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.error.ErrorCollector; +import com.ticxo.modelengine.api.error.IError; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchBehaviorParser; +import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchModel; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.type.PlayerLimb; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.function.Predicate; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class DefaultBehaviorParser implements BlockbenchBehaviorParser { + @Override + public void processModel(ErrorCollector collector, BlockbenchModel model, ModelBlueprint blueprint) { + this.searchBone(model, "hitbox", bone -> { + Hitbox mainHitbox = this.readHitbox(collector, model, bone); + if (mainHitbox == null) { + return false; + } else { + blueprint.setMainHitbox(mainHitbox); + return true; + } + }, () -> IError.NO_HITBOX.log(collector)); + this.searchBone(model, "shadow", bone -> { + float radius = this.readShadow(model, bone); + if (radius < 1.0E-5F) { + return false; + } else { + blueprint.setShadowRadius(radius); + return true; + } + }, null); + } + + @Override + public void processBone(ErrorCollector collector, BlockbenchModel model, BlockbenchModel.Group group, BlueprintBone bone) { + String name = this.readOptions(model, group, bone); + bone.setName(name); + } + + private void searchBone(BlockbenchModel model, String name, Predicate consumer, Runnable missing) { + BlockbenchModel.Group group = model.getGroup(name); + if (group != null && consumer.test(group)) { + model.removeGroup(group); + } else if (missing != null) { + missing.run(); + } + } + + private Hitbox readHitbox(ErrorCollector collector, BlockbenchModel model, BlockbenchModel.Group hitbox) { + Float[] boneOrigin = hitbox.getOrigin(); + + for (UUID uuid : hitbox.getElement()) { + BlockbenchModel.Element element = model.getElements().get(uuid); + if (element instanceof BlockbenchModel.Cube cube) { + Float[] cubeOrigin = cube.getOrigin(); + float eyeHeight = boneOrigin[1] <= 0.0F ? cubeOrigin[1] : boneOrigin[1]; + if (eyeHeight <= 0.0F) { + IError.BAD_EYE_HEIGHT.log(collector); + } + + return new Hitbox(cube.width() * 0.0625F, cube.height() * 0.0625F, cube.depth() * 0.0625F, eyeHeight * 0.0625F); + } + } + + return null; + } + + private float readShadow(BlockbenchModel model, BlockbenchModel.Group shadow) { + for (UUID uuid : shadow.getElement()) { + BlockbenchModel.Element element = model.getElements().get(uuid); + if (element instanceof BlockbenchModel.Cube cube) { + return Math.max(cube.width(), cube.depth()) * 0.03125F; + } + } + + return -1.0F; + } + + private String readOptions(BlockbenchModel model, BlockbenchModel.Group group, BlueprintBone bone) { + String name = bone.getName(); + Map> options = bone.getBehaviors(); + if (name.startsWith("h_")) { + name = name.substring(2); + options.put(BoneBehaviorTypes.HEAD.getId(), new HashMap<>()); + } else if (name.startsWith("hi_")) { + name = name.substring(3); + options.put(BoneBehaviorTypes.HEAD.getId(), new HashMap() { + { + this.put("inherited", true); + } + }); + } + + if (name.equals("mount")) { + options.put(BoneBehaviorTypes.MOUNT.getId(), new HashMap() { + { + this.put("driver", true); + } + }); + return name; + } else { + boolean isOBB = name.startsWith("ob_"); + if (!isOBB && !name.startsWith("b_")) { + String[] split = name.split("_(?![^\\[]*\\])"); + if (!group.getElement().isEmpty()) { + for (int i = 0; i < split.length; i++) { + String tag = split[i]; + String[] paramSplit = tag.split("\\[|;|\\]"); + tag = paramSplit[0]; + final HashMap paramMap = new HashMap<>(); + + for (int p = 1; p < paramSplit.length; p++) { + String[] pair = paramSplit[p].split("=", 2); + if (pair.length == 2) { + paramMap.put(pair[0], pair[1]); + } + } + + switch (tag) { + case "phead": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.HEAD); + } + }); + break; + case "prarm": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.RIGHT_ARM); + } + }); + break; + case "plarm": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.LEFT_ARM); + } + }); + break; + case "pbody": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.BODY); + } + }); + break; + case "prleg": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.RIGHT_LEG); + } + }); + break; + case "plleg": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.LEFT_LEG); + } + }); + break; + case "limb": + options.put(BoneBehaviorTypes.USER_LIMB.getId(), new HashMap() { + { + this.put("type", paramMap.get("type")); + } + }); + break; + case "tl": + options.put(BoneBehaviorTypes.TAIL.getId(), new HashMap() { + { + this.put("back_pivot", true); + } + }); + break; + case "tlf": + options.put(BoneBehaviorTypes.TAIL.getId(), new HashMap() { + { + this.put("back_pivot", false); + } + }); + break; + default: + StringBuilder builder = new StringBuilder(tag); + + for (int j = i + 1; j < split.length; j++) { + builder.append("_").append(split[j]); + } + + return builder.toString(); + } + } + + return name; + } else { + for (int i = 0; i < split.length; i++) { + String tag = split[i]; + String[] paramSplit = tag.split("\\[|;|\\]"); + tag = paramSplit[0]; + final HashMap paramMap = new HashMap<>(); + + for (int px = 1; px < paramSplit.length; px++) { + String[] pair = paramSplit[px].split("=", 2); + if (pair.length == 2) { + paramMap.put(pair[0], pair[1]); + } + } + + switch (tag) { + case "g": + options.put(BoneBehaviorTypes.GHOST.getId(), new HashMap<>()); + break; + case "tag": + options.put(BoneBehaviorTypes.NAMETAG.getId(), new HashMap<>()); + break; + case "p": + options.put(BoneBehaviorTypes.MOUNT.getId(), new HashMap() { + { + this.put("driver", false); + } + }); + break; + case "ir": + options.put(BoneBehaviorTypes.ITEM.getId(), new HashMap() { + { + this.put("display", ItemDisplayTransform.THIRDPERSON_RIGHTHAND); + } + }); + break; + case "il": + options.put(BoneBehaviorTypes.ITEM.getId(), new HashMap() { + { + this.put("display", ItemDisplayTransform.THIRDPERSON_LEFTHAND); + } + }); + break; + case "ih": + options.put(BoneBehaviorTypes.ITEM.getId(), new HashMap() { + { + this.put("display", ItemDisplayTransform.HEAD); + } + }); + break; + case "l": + options.put(BoneBehaviorTypes.LEASH.getId(), new HashMap<>()); + break; + case "phead": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.HEAD); + } + }); + break; + case "prarm": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.RIGHT_ARM); + } + }); + break; + case "plarm": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.LEFT_ARM); + } + }); + break; + case "pbody": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.BODY); + } + }); + break; + case "prleg": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.RIGHT_LEG); + } + }); + break; + case "plleg": + options.put(BoneBehaviorTypes.PLAYER_LIMB.getId(), new HashMap() { + { + this.put("limb", PlayerLimb.Limb.LEFT_LEG); + } + }); + break; + case "limb": + options.put(BoneBehaviorTypes.USER_LIMB.getId(), new HashMap() { + { + this.put("type", paramMap.get("type")); + } + }); + break; + case "seg": + options.put(BoneBehaviorTypes.SEGMENT.getId(), new HashMap() { + { + this.put("back_pivot", true); + } + }); + break; + case "segf": + options.put(BoneBehaviorTypes.SEGMENT.getId(), new HashMap() { + { + this.put("back_pivot", false); + } + }); + break; + case "tl": + options.put(BoneBehaviorTypes.TAIL.getId(), new HashMap() { + { + this.put("back_pivot", true); + } + }); + break; + case "tlf": + options.put(BoneBehaviorTypes.TAIL.getId(), new HashMap() { + { + this.put("back_pivot", false); + } + }); + break; + default: + StringBuilder builder = new StringBuilder(tag); + + for (int j = i + 1; j < split.length; j++) { + builder.append("_").append(split[j]); + } + + return builder.toString(); + } + } + + return name; + } + } else { + HashMap map = new HashMap<>(); + if (isOBB) { + map.put("obb", true); + } + + for (UUID uuid : group.getElement()) { + BlockbenchModel.Element element = model.getElements().get(uuid); + if (element instanceof BlockbenchModel.Cube cube) { + map.put("dimension", new Hitbox(cube.width() * 0.0625, cube.height() * 0.0625, cube.depth() * 0.0625, 0.0)); + Float[] from = cube.getFrom(); + Float[] to = cube.getTo(); + map.put("origin", new Vector3f((from[0] + to[0]) * -0.03125F, (from[1] + to[1]) * 0.03125F, (from[2] + to[2]) * -0.03125F)); + Float[] rotation = cube.getRotation(); + map.put("rotation", rotation != null ? new Vector3f(-rotation[0], rotation[1], -rotation[2]).mul((float) (Math.PI / 180.0)) : new Vector3f()); + Float[] origin = cube.getOrigin(); + map.put("cube_origin", new Vector3f(origin[0] * -0.0625F, origin[1] * 0.0625F, origin[2] * -0.0625F)); + break; + } + } + + options.put(BoneBehaviorTypes.SUB_HITBOX.getId(), map); + return name; + } + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/json/MCMetaDeserializer.java b/core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/json/MCMetaDeserializer.java new file mode 100644 index 0000000..82c7d9d --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/parser/blockbench/json/MCMetaDeserializer.java @@ -0,0 +1,38 @@ +package com.ticxo.modelengine.core.generator.parser.blockbench.json; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.ticxo.modelengine.api.generator.assets.BlueprintTexture; +import com.ticxo.modelengine.api.utils.data.GSONUtils; +import java.lang.reflect.Type; + +public class MCMetaDeserializer implements JsonDeserializer { + public BlueprintTexture.MCMeta deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + JsonObject animation = GSONUtils.get(jsonElement, "animation", JsonElement::getAsJsonObject); + if (animation == null) { + return null; + } else { + BlueprintTexture.MCMeta meta = new BlueprintTexture.MCMeta(); + meta.setInterpolate(GSONUtils.get(animation, "interpolate", JsonElement::getAsBoolean)); + meta.setWidth(GSONUtils.get(animation, "width", JsonElement::getAsInt)); + meta.setHeight(GSONUtils.get(animation, "height", JsonElement::getAsInt)); + meta.setFrametime(GSONUtils.get(animation, "frametime", JsonElement::getAsInt)); + GSONUtils.ifArray(animation, "frames", element -> { + if (element.isJsonPrimitive()) { + meta.addFrame(element.getAsInt()); + } else if (element.isJsonObject()) { + JsonObject frameObject = element.getAsJsonObject(); + Integer index = GSONUtils.get(frameObject, "index", JsonElement::getAsInt); + Integer time = GSONUtils.get(frameObject, "time", JsonElement::getAsInt); + if (index != null && time != null) { + meta.addFrame(index, time); + } + } + }); + return meta; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/processed/ProcessedBone.java b/core/src/main/java/com/ticxo/modelengine/core/generator/processed/ProcessedBone.java new file mode 100644 index 0000000..1873586 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/processed/ProcessedBone.java @@ -0,0 +1,200 @@ +package com.ticxo.modelengine.core.generator.processed; + +import com.ticxo.modelengine.api.generator.assets.JavaItemModel; +import com.ticxo.modelengine.api.generator.assets.ModelAssets; +import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchModel; +import com.ticxo.modelengine.api.utils.math.Direction; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.core.generator.util.ItemGroup; +import com.ticxo.modelengine.core.generator.util.RotationSolver; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaterniond; +import org.joml.Vector3d; +import org.joml.Vector3f; + +public class ProcessedBone { + private final String name; + private final Vector3f boneOrigin; + private final Vector3f rotation; + private final Set cubes = new LinkedHashSet<>(); + private final Set groups = new LinkedHashSet<>(); + private final Set models = new LinkedHashSet<>(); + private int scale; + + public void splitModels(BlockbenchModel model, ModelAssets assets) { + RotationSolver.solve(this.groups, this.cubes); + float maxDistToOrigin = 0.0F; + + for (ItemGroup group : this.groups) { + JavaItemModel jiModel = group.toJavaItemModel(this.name, model, assets); + maxDistToOrigin = Math.max(jiModel.getMaxDistToOrigin(), maxDistToOrigin); + this.models.add(jiModel); + } + + for (JavaItemModel m : this.models) { + m.setMaxDistToOrigin(maxDistToOrigin); + this.scale = m.scaleToFit(); + } + } + + public String getName() { + return this.name; + } + + public Vector3f getBoneOrigin() { + return this.boneOrigin; + } + + public Vector3f getRotation() { + return this.rotation; + } + + public Set getCubes() { + return this.cubes; + } + + public Set getGroups() { + return this.groups; + } + + public Set getModels() { + return this.models; + } + + public int getScale() { + return this.scale; + } + + public ProcessedBone(String name, Vector3f boneOrigin, Vector3f rotation) { + this.name = name; + this.boneOrigin = boneOrigin; + this.rotation = rotation; + } + + public static class Cube { + private final String name; + private final Vector3d origin; + private final Vector3d rotation; + private final Quaterniond quaternion; + private final Vector3d from; + private final Vector3d to; + private final Map faces; + private final float inflate; + + public Cube(String name, Vector3d origin, Vector3d rotation, Vector3d from, Vector3d to, Map faces, float inflate) { + this.name = name; + this.origin = new Vector3d(origin); + this.rotation = new Vector3d(rotation); + this.quaternion = TMath.fromEulerZYX(rotation); + this.from = new Vector3d(from); + this.to = new Vector3d(to); + this.faces = faces; + this.inflate = inflate; + } + + @Override + public String toString() { + return this.name + ": " + this.rotation.toString(NumberFormat.getInstance()); + } + + public List getCorners() { + return new ArrayList() { + { + this.add(new Vector3d(Cube.this.from.x, Cube.this.from.y, Cube.this.from.z)); + this.add(new Vector3d(Cube.this.from.x, Cube.this.from.y, Cube.this.to.z)); + this.add(new Vector3d(Cube.this.from.x, Cube.this.to.y, Cube.this.from.z)); + this.add(new Vector3d(Cube.this.from.x, Cube.this.to.y, Cube.this.to.z)); + this.add(new Vector3d(Cube.this.to.x, Cube.this.from.y, Cube.this.from.z)); + this.add(new Vector3d(Cube.this.to.x, Cube.this.from.y, Cube.this.to.z)); + this.add(new Vector3d(Cube.this.to.x, Cube.this.to.y, Cube.this.from.z)); + this.add(new Vector3d(Cube.this.to.x, Cube.this.to.y, Cube.this.to.z)); + } + }; + } + + public void rotate(Quaterniond rot) { + this.from.sub(this.origin); + this.to.sub(this.origin); + this.origin.rotate(rot); + this.quaternion.premul(rot); + this.rotation.set(TMath.fixEuler(TMath.toEulerZYX(this.quaternion))); + this.from.add(this.origin); + this.to.add(this.origin); + } + + @Nullable + public JavaItemModel.JavaElement.RotationSingle rotation() { + int zeros = 0; + float[] origin = TMath.unwrap(this.origin); + float[] rotation = TMath.unwrap(this.rotation); + + for (float angle : rotation) { + zeros += angle == 0.0F ? 1 : 0; + } + + if (zeros == 3) { + return null; + } else { + JavaItemModel.JavaElement.RotationSingle javaRotation = new JavaItemModel.JavaElement.RotationSingle(); + int i = TMath.absMax(rotation[0], rotation[1], rotation[2]); + + javaRotation.setAxis(switch (i) { + case 1 -> "y"; + case 2 -> "z"; + default -> "x"; + }); + float angle = Math.round(rotation[i] / 22.5F) * 22.5F; + javaRotation.setAngle(angle); + javaRotation.origin(origin); + return javaRotation; + } + } + + public String getName() { + return this.name; + } + + public Vector3d getOrigin() { + return this.origin; + } + + public Vector3d getRotation() { + return this.rotation; + } + + public Quaterniond getQuaternion() { + return this.quaternion; + } + + public Vector3d getFrom() { + return this.from; + } + + public Vector3d getTo() { + return this.to; + } + + public Map getFaces() { + return this.faces; + } + + public float getInflate() { + return this.inflate; + } + } + + public record Face(ProcessedBone.UV uv, int texture) { + public boolean isEmpty() { + return TMath.isSimilar(this.uv.u1(), this.uv.u2()) || TMath.isSimilar(this.uv.v1, this.uv.v2); + } + } + + public record UV(float u1, float v1, float u2, float v2, int rotation) { + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/skin/FaceMapper.java b/core/src/main/java/com/ticxo/modelengine/core/generator/skin/FaceMapper.java new file mode 100644 index 0000000..888885c --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/skin/FaceMapper.java @@ -0,0 +1,61 @@ +package com.ticxo.modelengine.core.generator.skin; + +import com.ticxo.modelengine.api.utils.math.TMath; +import java.util.function.BiConsumer; + +public record FaceMapper(String sourceTexture, float[] from, FaceMapper.Face to) { + public float[] getSourcePixel(float x, float y) { + float fx1 = this.from[0]; + float fy1 = this.from[1]; + float fx2 = this.from[2]; + float fy2 = this.from[3]; + float tx1 = this.to.uv[0]; + float ty1 = this.to.uv[1]; + float tx2 = this.to.uv[2]; + float ty2 = this.to.uv[3]; + float txr = TMath.invLerp(tx1, tx2, x); + float tyr = TMath.invLerp(ty1, ty2, y); + return new float[]{TMath.lerp(fx1, fx2, txr), TMath.lerp(fy1, fy2, tyr)}; + } + + public static enum Face { + NORTH(new int[]{8, 8, 16, 16}), + EAST(new int[]{0, 8, 8, 16}), + SOUTH(new int[]{24, 8, 32, 16}), + WEST(new int[]{16, 8, 24, 16}), + UP(new int[]{16, 8, 8, 0}), + DOWN(new int[]{24, 0, 16, 8}), + NORTH_HAT(new int[]{40, 8, 48, 16}), + EAST_HAT(new int[]{32, 8, 40, 16}), + SOUTH_HAT(new int[]{56, 8, 64, 16}), + WEST_HAT(new int[]{48, 8, 56, 16}), + UP_HAT(new int[]{48, 8, 40, 0}), + DOWN_HAT(new int[]{56, 0, 48, 8}); + + private final int[] uv; + + public void forPixel(BiConsumer consumer) { + for (int x = Math.min(this.uv[0], this.uv[2]); x < Math.max(this.uv[0], this.uv[2]); x++) { + for (int y = Math.min(this.uv[1], this.uv[3]); y < Math.max(this.uv[1], this.uv[3]); y++) { + consumer.accept(x, y); + } + } + } + + public static FaceMapper.Face getFace(String val, boolean hat) { + return switch (val) { + case "north" -> hat ? NORTH_HAT : NORTH; + case "east" -> hat ? EAST_HAT : EAST; + case "south" -> hat ? SOUTH_HAT : SOUTH; + case "west" -> hat ? WEST_HAT : WEST; + case "up" -> hat ? UP_HAT : UP; + case "down" -> hat ? DOWN_HAT : DOWN; + default -> throw new IllegalStateException("Unexpected value: " + val); + }; + } + + private Face(int[] uv) { + this.uv = uv; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/skin/MineSkinGeneratorService.java b/core/src/main/java/com/ticxo/modelengine/core/generator/skin/MineSkinGeneratorService.java new file mode 100644 index 0000000..f923d3a --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/skin/MineSkinGeneratorService.java @@ -0,0 +1,94 @@ +package com.ticxo.modelengine.core.generator.skin; + +import com.ticxo.modelengine.api.generator.skin.SkinGeneratorService; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.io.ByteArrayInputStream; +import java.util.concurrent.CompletableFuture; +import java.util.logging.Logger; +import org.mineskin.JsoupRequestHandler; +import org.mineskin.MineSkinClient; +import org.mineskin.data.Visibility; +import org.mineskin.exception.MineSkinRequestException; +import org.mineskin.options.GenerateQueueOptions; +import org.mineskin.request.GenerateRequest; +import org.mineskin.response.MineSkinResponse; + +public class MineSkinGeneratorService implements SkinGeneratorService { + private boolean enabled; + private MineSkinClient client; + + @Override + public void onReload() { + String key = ConfigProperty.MINESKIN_API_KEY.getString(); + if (key != null && !key.isBlank()) { + this.client = MineSkinClient.builder() + .requestHandler(JsoupRequestHandler::new) + .userAgent("ModelEngine/R4.0.9") + .apiKey(key) + .generateQueueOptions(GenerateQueueOptions.createAuto()) + .build(); + quietenClientLogger(); + this.enabled = true; + } else { + TLogger.warn("Unable to activate MineSkin skin generation: Empty API Key"); + this.enabled = false; + } + } + + private static void quietenClientLogger() { + Logger.getLogger("org.mineskin.MineSkinClient").setFilter(record -> { + Throwable thrown = record.getThrown(); + if (thrown == null) { + return true; + } else { + TLogger.warn("Failed to communicate with MineSkin: " + summarize(thrown)); + return false; + } + }); + } + + private static String summarize(Throwable thrown) { + for (Throwable cause = thrown; cause != null; cause = cause.getCause()) { + if (cause instanceof MineSkinRequestException requestException) { + MineSkinResponse response = requestException.getResponse(); + return response != null ? "HTTP " + response.getStatus() + " - " + requestException.getMessage() : requestException.getMessage(); + } + + if (cause.getCause() == cause) { + break; + } + } + + Throwable root = thrown; + + while (root.getCause() != null && root.getCause() != root) { + root = root.getCause(); + } + + String message = root.getMessage(); + return root.getClass().getSimpleName() + (message != null ? ": " + firstLine(message) : ""); + } + + private static String firstLine(String message) { + int newline = message.indexOf(10); + String line = newline < 0 ? message : message.substring(0, newline); + return line.length() > 120 ? line.substring(0, 120) + "..." : line; + } + + @Override + public CompletableFuture generate(byte[] rawImage) { + GenerateRequest request = GenerateRequest.upload(new ByteArrayInputStream(rawImage)).visibility(Visibility.UNLISTED); + return this.client + .queue() + .submit(request) + .thenCompose(queueResponse -> queueResponse.getJob().waitForCompletion(this.client)) + .thenCompose(jobResponse -> jobResponse.getOrLoadSkin(this.client)) + .thenApply(skinInfo -> skinInfo.texture().url().skin()); + } + + @Override + public boolean isEnabled() { + return this.enabled; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/skin/PlayerMapper.java b/core/src/main/java/com/ticxo/modelengine/core/generator/skin/PlayerMapper.java new file mode 100644 index 0000000..4be26f2 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/skin/PlayerMapper.java @@ -0,0 +1,86 @@ +package com.ticxo.modelengine.core.generator.skin; + +import com.ticxo.modelengine.api.generator.skin.LimbData; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import javax.imageio.ImageIO; + +public class PlayerMapper { + private final Map limbData = new HashMap<>(); + private final Map textureReference = new HashMap<>(); + private final Map> faceMappers = new HashMap<>(); + + public void registerLimbData(LimbData data) { + this.limbData.put(data.limbType(), data); + } + + public LimbData getLimbData(String data) { + return this.limbData.get(data); + } + + public void registerTextureSource(String name, BufferedImage texture) { + this.textureReference.put(name, texture); + } + + public void registerFaceMapper(String name, FaceMapper mapper) { + this.faceMappers.computeIfAbsent(name, s -> new HashSet<>()).add(mapper); + } + + public Map generateAll(Map placeholderReference) { + return this.generate(this.faceMappers.keySet(), placeholderReference); + } + + public Map generate(Collection parts, Map placeholderReference) { + HashMap map = new HashMap<>(); + + for (String key : parts) { + try { + byte[] data = this.generatePartTexture(key, placeholderReference); + if (data.length > 0) { + map.put(key, data); + } + } catch (IOException var7) { + var7.printStackTrace(); + } + } + + return map; + } + + public byte[] generatePartTexture(String part, Map placeholderReference) throws IOException { + Set mappers = this.faceMappers.get(part); + if (mappers != null && !mappers.isEmpty()) { + BufferedImage image = new BufferedImage(64, 64, 2); + + for (FaceMapper mapper : mappers) { + BufferedImage texture = placeholderReference.get(mapper.sourceTexture()); + if (texture == null) { + texture = this.textureReference.get(mapper.sourceTexture()); + if (texture == null) { + continue; + } + } + + BufferedImage finalTexture = texture; + mapper.to().forPixel((x, y) -> { + float[] source = mapper.getSourcePixel(x.intValue(), y.intValue()); + int xx = (int)(source[0] * (finalTexture.getWidth() / 64.0F)); + int yy = (int)(source[1] * (finalTexture.getHeight() / 64.0F)); + image.setRGB(x, y, finalTexture.getRGB(xx, yy)); + }); + } + + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + ImageIO.write(image, "png", byteStream); + return byteStream.toByteArray(); + } else { + return new byte[0]; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/skin/SkinSplitterImpl.java b/core/src/main/java/com/ticxo/modelengine/core/generator/skin/SkinSplitterImpl.java new file mode 100644 index 0000000..0ab5c60 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/skin/SkinSplitterImpl.java @@ -0,0 +1,142 @@ +package com.ticxo.modelengine.core.generator.skin; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchDeserializer; +import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchModel; +import com.ticxo.modelengine.api.generator.skin.LimbData; +import com.ticxo.modelengine.api.generator.skin.SkinSplitter; +import com.ticxo.modelengine.api.utils.TFile; +import com.ticxo.modelengine.api.utils.math.TMath; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Map.Entry; +import javax.imageio.ImageIO; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class SkinSplitterImpl implements SkinSplitter { + private static final String PLACEHOLDER_SKIN = ""; + private final Gson gson = new GsonBuilder().registerTypeAdapter(BlockbenchModel.class, new BlockbenchDeserializer()).create(); + private final File internalSteveMapped; + private final File internalAlexMapped; + private PlayerMapper steveMapper; + private PlayerMapper alexMapper; + + public void copyMapped(ModelEngineAPI plugin) { + TFile.copyResource(plugin, this.internalSteveMapped, "internal/steve_mapped.bbmodel"); + TFile.copyResource(plugin, this.internalAlexMapped, "internal/alex_mapped.bbmodel"); + } + + @Override + public void reloadMapping() { + try { + this.steveMapper = this.createSkinMaps((BlockbenchModel)this.gson.fromJson(new FileReader(this.internalSteveMapped), BlockbenchModel.class)); + this.alexMapper = this.createSkinMaps((BlockbenchModel)this.gson.fromJson(new FileReader(this.internalAlexMapped), BlockbenchModel.class)); + } catch (IOException var2) { + var2.printStackTrace(); + } + } + + private PlayerMapper createSkinMaps(BlockbenchModel model) { + PlayerMapper playerTemplate = new PlayerMapper(); + HashMap texMap = new HashMap<>(); + + for (Entry entry : model.getTextures().entrySet()) { + BlockbenchModel.Texture texture = entry.getValue(); + if (!texture.getName().equals("")) { + BufferedImage image = TFile.toImage(texture.getSource()); + playerTemplate.registerTextureSource(texture.getName(), image); + } + + texMap.put(entry.getKey(), texture.getName()); + } + + Map groups = model.getFlatOutlinerByName(); + + for (Entry entry : groups.entrySet()) { + String boneId = entry.getKey(); + if (boneId.equals("head")) { + playerTemplate.registerLimbData(new LimbData(boneId, new Vector3f(0.0F, 0.5F, 0.0F), new Vector3f(1.0F), true)); + } else { + BlockbenchModel.Group group = entry.getValue(); + if (!group.getElement().isEmpty()) { + List cubes = group.getElement() + .stream() + .map(uuid -> model.getElements().get(uuid)) + .map(element -> element instanceof BlockbenchModel.Cube cubex ? cubex : null) + .filter(Objects::nonNull) + .toList(); + if (!cubes.isEmpty()) { + Vector3f origin = new Vector3f(0.0F); + Vector3f scale = new Vector3f(1.0F); + + for (BlockbenchModel.Cube cube : cubes) { + boolean hatLayer = cube.getName().startsWith("hat_"); + if (!hatLayer) { + origin.set(cube.centerX(), cube.maxY(), cube.centerZ()).sub(TMath.wrap(group.getOrigin())).mul(-0.0625F, 0.0625F, -0.0625F); + scale.set(cube.width(), cube.height(), cube.depth()).mul(0.125F); + } + + for (Entry faceEntry : cube.getFaces().entrySet()) { + String texName = texMap.get(faceEntry.getValue().getTexture()); + if (texName != null) { + FaceMapper.Face face = FaceMapper.Face.getFace(faceEntry.getKey(), hatLayer); + Float[] uv = faceEntry.getValue().getUv(); + FaceMapper faceMapper = new FaceMapper(texName, new float[]{uv[0], uv[1], uv[2], uv[3]}, face); + playerTemplate.registerFaceMapper(boneId, faceMapper); + } + } + } + + playerTemplate.registerLimbData(new LimbData(boneId, origin, scale, false)); + } + } + } + } + + return playerTemplate; + } + + @Override + public LimbData getLimb(String id, boolean slim) { + return (slim ? this.alexMapper : this.steveMapper).getLimbData(id); + } + + @Override + public Map splitSkin(byte[] skinData, boolean slim) { + return this.split(skinData, slim, null); + } + + @Override + public Map splitSkin(byte[] skinData, boolean slim, Collection limbTypes) { + return this.split(skinData, slim, limbTypes); + } + + private Map split(byte[] skinData, boolean slim, @Nullable Collection limbTypes) { + try { + BufferedImage skinImage = ImageIO.read(new ByteArrayInputStream(skinData)); + HashMap placeholder = new HashMap<>(); + placeholder.put("", skinImage); + PlayerMapper mapper = slim ? this.alexMapper : this.steveMapper; + return limbTypes == null ? mapper.generateAll(placeholder) : mapper.generate(limbTypes, placeholder); + } catch (IOException var7) { + var7.printStackTrace(); + return new HashMap<>(); + } + } + + public SkinSplitterImpl(File internalSteveMapped, File internalAlexMapped) { + this.internalSteveMapped = internalSteveMapped; + this.internalAlexMapped = internalAlexMapped; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/util/HashedVector3d.java b/core/src/main/java/com/ticxo/modelengine/core/generator/util/HashedVector3d.java new file mode 100644 index 0000000..8d8d05a --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/util/HashedVector3d.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.core.generator.util; + +import com.ticxo.modelengine.api.utils.math.Axis; +import java.util.Objects; +import org.joml.Vector3d; + +public class HashedVector3d extends Vector3d { + private static final int PRECISION = 10000; + private final Axis axis; + + public HashedVector3d(Axis axis, double x, double y, double z) { + super(x, y, z); + this.axis = axis; + } + + public HashedVector3d() { + this.axis = Axis.X; + } + + public int hashCode() { + return Objects.hash(this.axis, (int)Math.round(this.x * 10000.0), (int)Math.round(this.y * 10000.0), (int)Math.round(this.z * 10000.0)); + } + + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (obj == null) { + return false; + } else { + return this.getClass() != obj.getClass() ? false : this.hashCode() == obj.hashCode(); + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/util/IllegalRotationSolver.java b/core/src/main/java/com/ticxo/modelengine/core/generator/util/IllegalRotationSolver.java new file mode 100644 index 0000000..1745474 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/util/IllegalRotationSolver.java @@ -0,0 +1,120 @@ +package com.ticxo.modelengine.core.generator.util; + +import com.ticxo.modelengine.api.utils.data.Triple; +import com.ticxo.modelengine.api.utils.math.Axis; +import com.ticxo.modelengine.api.utils.math.Direction; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.core.generator.processed.ProcessedBone; +import java.util.HashMap; +import java.util.List; +import java.util.Map.Entry; +import org.joml.Quaterniond; +import org.joml.Vector3d; +import org.joml.Vector3dc; + +public class IllegalRotationSolver { + private static final List AXES = List.of(Axis.X.getVector(), Axis.Y.getVector(), Axis.Z.getVector()); + + public static ProcessedBone.Cube solve(ProcessedBone.Cube cube) { + if (isLegal(cube)) { + return cube; + } else { + Quaterniond quaternion = cube.getQuaternion(); + HashMap> uvs = new HashMap<>(); + + for (Entry entry : cube.getFaces().entrySet()) { + Direction dir = entry.getKey(); + ProcessedBone.Face uv = entry.getValue(); + uvs.put(dir, new Triple<>(dir.getNormal().rotate(quaternion), dir.getUvUp().rotate(quaternion), uv)); + } + + List corners = cube.getCorners(); + corners.forEach(vector3d -> vector3d.sub(cube.getOrigin()).rotate(quaternion).add(cube.getOrigin())); + Vector3d srcDir = new Vector3d(0.0, 0.0, 1.0).rotate(quaternion); + Vector3d dstAxis = closestAxis(srcDir); + double dot = srcDir.dot(dstAxis); + Quaterniond undoQuat; + if (TMath.isSimilar(dot, 1.0)) { + srcDir = new Vector3d(0.0, 1.0, 0.0).rotate(quaternion); + dstAxis = closestAxis(srcDir); + dot = srcDir.dot(dstAxis); + if (TMath.isSimilar(dot, 1.0)) { + undoQuat = new Quaterniond(); + } else { + Vector3d cross = srcDir.cross(dstAxis, new Vector3d()).normalize(); + undoQuat = new Quaterniond().rotateAxis(Math.acos(dot), cross); + } + } else { + Vector3d cross = srcDir.cross(dstAxis, new Vector3d()).normalize(); + undoQuat = new Quaterniond().rotateAxis(Math.acos(dot), cross); + } + + HashMap newUVs = new HashMap<>(); + + for (Entry> entry : uvs.entrySet()) { + Triple triple = entry.getValue(); + Vector3d currNormal = triple.getFirst().rotate(undoQuat); + Direction currDir = Direction.fromNormal(currNormal); + if (currDir != null) { + Vector3d currUVUp = currDir.getUvUp(); + Vector3d targetUVUp = triple.getSecond().rotate(undoQuat); + int angle = 0; + double upDot = targetUVUp.dot(currUVUp); + if (TMath.isSimilar(upDot, -1.0)) { + angle = 180; + } else if (TMath.isSimilar(upDot, 0.0)) { + Vector3d cross = targetUVUp.cross(currUVUp, new Vector3d()); + angle = cross.dot(currNormal) > 0.0 ? 90 : 270; + } + + ProcessedBone.Face face = triple.getThird(); + ProcessedBone.UV uv = face.uv(); + ProcessedBone.Face tFace = new ProcessedBone.Face( + new ProcessedBone.UV(uv.u1(), uv.v1(), uv.u2(), uv.v2(), (uv.rotation() + angle) % 360), face.texture() + ); + newUVs.put(currDir, tFace); + } + } + + Vector3d from = new Vector3d(2.147483647E9); + Vector3d to = new Vector3d(-2.1474836E9F); + corners.forEach(vector3d -> { + Vector3d vec = vector3d.sub(cube.getOrigin()).rotate(undoQuat).add(cube.getOrigin()); + from.set(Math.min(from.x, vec.x), Math.min(from.y, vec.y), Math.min(from.z, vec.z)); + to.set(Math.max(to.x, vec.x), Math.max(to.y, vec.y), Math.max(to.z, vec.z)); + }); + Vector3d rotation = TMath.fixEuler(TMath.toEulerZYX(undoQuat.invert())); + return new ProcessedBone.Cube(cube.getName(), cube.getOrigin(), rotation, from, to, newUVs, cube.getInflate()); + } + } + + private static Vector3d closestAxis(Vector3d dir) { + if (TMath.isSimilar(dir.lengthSquared(), 0.0)) { + return new Vector3d((Vector3dc)AXES.get(2)); + } else { + Vector3d closest = null; + double dot = 0.0; + + for (Vector3d axis : AXES) { + double d = Math.abs(dir.dot(axis)); + if (d > dot) { + dot = d; + closest = axis; + } + } + + if (closest == null) { + return new Vector3d((Vector3dc)AXES.get(2)); + } else { + return closest.dot(dir) > 0.0 ? new Vector3d(closest) : closest.negate(new Vector3d()); + } + } + } + + private static boolean isLegal(ProcessedBone.Cube cube) { + Vector3d rot = cube.getRotation(); + return TMath.isAlmostBetween(rot.x, -45.0, 45.0) && TMath.isInterval(rot.x, 22.5) && TMath.isSimilar(rot.y, 0.0) && TMath.isSimilar(rot.z, 0.0) + || TMath.isAlmostBetween(rot.y, -45.0, 45.0) && TMath.isInterval(rot.y, 22.5) && TMath.isSimilar(rot.x, 0.0) && TMath.isSimilar(rot.z, 0.0) + || TMath.isAlmostBetween(rot.z, -45.0, 45.0) && TMath.isInterval(rot.z, 22.5) && TMath.isSimilar(rot.x, 0.0) && TMath.isSimilar(rot.y, 0.0); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/util/ItemGroup.java b/core/src/main/java/com/ticxo/modelengine/core/generator/util/ItemGroup.java new file mode 100644 index 0000000..0b4f8c7 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/util/ItemGroup.java @@ -0,0 +1,104 @@ +package com.ticxo.modelengine.core.generator.util; + +import com.ticxo.modelengine.api.generator.assets.JavaDisplay; +import com.ticxo.modelengine.api.generator.assets.JavaItemModel; +import com.ticxo.modelengine.api.generator.assets.ModelAssets; +import com.ticxo.modelengine.api.generator.parser.blockbench.BlockbenchModel; +import com.ticxo.modelengine.api.utils.MiscUtils; +import com.ticxo.modelengine.api.utils.math.Direction; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.core.generator.processed.ProcessedBone; +import java.text.NumberFormat; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import org.joml.Quaterniond; +import org.joml.Vector3d; + +public record ItemGroup(int debug, Quaterniond displayQuaternion, Vector3d displayRotation, List cubes) { + public JavaItemModel toJavaItemModel(String name, BlockbenchModel model, ModelAssets assets) { + JavaItemModel javaItem = new JavaItemModel(); + javaItem.setName(name); + + for (ProcessedBone.Cube cube : this.cubes) { + JavaItemModel.JavaElement element = new JavaItemModel.JavaElement(); + element.from(TMath.unwrap(cube.getFrom()), cube.getInflate()); + element.to(TMath.unwrap(cube.getTo()), cube.getInflate()); + element.setRotation(cube.rotation()); + + for (Entry faceEntry : cube.getFaces().entrySet()) { + Direction dir = faceEntry.getKey(); + ProcessedBone.Face bbFace = faceEntry.getValue(); + if (!bbFace.isEmpty()) { + int id = bbFace.texture(); + if (id < assets.getTextures().size()) { + BlockbenchModel.Texture tex = model.getTextures().get(id); + JavaItemModel.JavaElement.Face face = new JavaItemModel.JavaElement.Face(); + face.setRotation(bbFace.uv().rotation()); + face.uv( + MiscUtils.or(tex.getUv_width(), model.getResolution().getWidth()), + MiscUtils.or(tex.getUv_height(), model.getResolution().getHeight()), + new float[]{bbFace.uv().u1(), bbFace.uv().v1(), bbFace.uv().u2(), bbFace.uv().v2()} + ); + face.setTexture("#" + id); + element.getFaces().put(dir.name().toLowerCase(Locale.ENGLISH), face); + Map textures = javaItem.getTextures(); + textures.computeIfAbsent(String.valueOf(id), s -> assets.getTextures().get(id).getPath().toString()); + if (textures.size() == 1) { + textures.computeIfAbsent("particle", s -> "#" + id); + } + } + } + } + + javaItem.addElement(element); + } + + javaItem.setDisplay( + JavaDisplay.THIRDPERSON_RIGHTHAND, + JavaDisplay.Transform.ROTATION, + (float)this.displayRotation.x, + (float)this.displayRotation.y, + (float)this.displayRotation.z + ); + javaItem.setDisplay( + JavaDisplay.FIRSTPERSON_RIGHTHAND, + JavaDisplay.Transform.ROTATION, + (float)this.displayRotation.x, + (float)this.displayRotation.y, + (float)this.displayRotation.z + ); + javaItem.setDisplay( + JavaDisplay.GROUND, JavaDisplay.Transform.ROTATION, (float)this.displayRotation.x, (float)this.displayRotation.y, (float)this.displayRotation.z + ); + javaItem.setDisplay( + JavaDisplay.HEAD, JavaDisplay.Transform.ROTATION, (float)this.displayRotation.x, (float)this.displayRotation.y, (float)this.displayRotation.z + ); + javaItem.setDisplay( + JavaDisplay.FIXED, JavaDisplay.Transform.ROTATION, (float)this.displayRotation.x, (float)this.displayRotation.y, (float)this.displayRotation.z + ); + Vector3d guiRotation = TMath.toEulerXYZ(TMath.fromEulerXYZ(new Vector3d(30.0, 225.0, 0.0)).mul(this.displayQuaternion)); + javaItem.setDisplay(JavaDisplay.GUI, JavaDisplay.Transform.ROTATION, (float)guiRotation.x, (float)guiRotation.y, (float)guiRotation.z); + javaItem.setDisplay( + JavaDisplay.THIRDPERSON_LEFTHAND, + JavaDisplay.Transform.ROTATION, + (float)this.displayRotation.x, + (float)(-this.displayRotation.y), + (float)(-this.displayRotation.z) + ); + javaItem.setDisplay( + JavaDisplay.FIRSTPERSON_LEFTHAND, + JavaDisplay.Transform.ROTATION, + (float)this.displayRotation.x, + (float)(-this.displayRotation.y), + (float)(-this.displayRotation.z) + ); + return javaItem; + } + + @Override + public String toString() { + return "ItemGroup{debug=" + this.debug + ", displayRotation=" + this.displayRotation.toString(NumberFormat.getInstance()) + ", cubes=" + this.cubes + "}"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/util/PlaneGroup.java b/core/src/main/java/com/ticxo/modelengine/core/generator/util/PlaneGroup.java new file mode 100644 index 0000000..5e26984 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/util/PlaneGroup.java @@ -0,0 +1,40 @@ +package com.ticxo.modelengine.core.generator.util; + +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.core.generator.processed.ProcessedBone; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.IntSet; +import java.text.NumberFormat; +import org.joml.Quaterniond; +import org.joml.Vector3d; + +public record PlaneGroup(Vector3d axis, int modAngle, Quaterniond origin, Quaterniond invOrigin, IntSet cubes) { + @Override + public String toString() { + return "PlaneGroup{axis=" + + this.axis + + ", modAngle=" + + this.modAngle + + ", origin=" + + TMath.toEulerZYX(this.origin).toString(NumberFormat.getInstance()) + + ", invOrigin=" + + TMath.toEulerZYX(this.invOrigin).toString(NumberFormat.getInstance()) + + ", cubes=" + + this.cubes + + "}"; + } + + public String toString(Int2ObjectMap map) { + return "PlaneGroup{axis=" + + this.axis + + ", modAngle=" + + this.modAngle + + ", origin=" + + TMath.toEulerZYX(this.origin).toString(NumberFormat.getInstance()) + + ", invOrigin=" + + TMath.toEulerZYX(this.invOrigin).toString(NumberFormat.getInstance()) + + ", cubes=" + + map.int2ObjectEntrySet().stream().filter(cubeEntry -> this.cubes.contains(cubeEntry.getIntKey())).toList() + + "}"; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/generator/util/RotationSolver.java b/core/src/main/java/com/ticxo/modelengine/core/generator/util/RotationSolver.java new file mode 100644 index 0000000..4d4b05b --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/generator/util/RotationSolver.java @@ -0,0 +1,343 @@ +package com.ticxo.modelengine.core.generator.util; + +import com.ticxo.modelengine.api.utils.math.Axis; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.core.generator.processed.ProcessedBone; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntIterator; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntListIterator; +import it.unimi.dsi.fastutil.ints.IntSet; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; +import it.unimi.dsi.fastutil.objects.ObjectIterator; +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Set; +import java.util.Map.Entry; +import org.joml.Quaterniond; +import org.joml.Vector3d; +import org.joml.Vector3dc; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RotationSolver { + private static final Logger log = LoggerFactory.getLogger(RotationSolver.class); + private static final List CARDINAL_AXES = new ArrayList() { + { + this.add(new Vector3d(1.0, 0.0, 0.0)); + this.add(new Vector3d(0.0, 1.0, 0.0)); + this.add(new Vector3d(0.0, 0.0, 1.0)); + this.add(new Vector3d(-1.0, 0.0, 0.0)); + this.add(new Vector3d(0.0, -1.0, 0.0)); + this.add(new Vector3d(0.0, 0.0, -1.0)); + } + }; + private final Int2ObjectMap cubes = new Int2ObjectOpenHashMap(); + private final Int2ObjectMap> axes = new Int2ObjectOpenHashMap(); + + public static void solve(Collection result, Collection cubes) { + RotationSolver solver = new RotationSolver(); + solver.initialize(result, cubes); + solver.solve(result); + } + + private void initialize(Collection result, Collection collection) { + int cubeId = 0; + ArrayList list = new ArrayList<>(); + + for (ProcessedBone.Cube cube : collection) { + if (isLegal(cube)) { + list.add(IllegalRotationSolver.solve(cube)); + } else { + this.cubes.put(cubeId++, cube); + } + } + + if (!list.isEmpty()) { + result.add(new ItemGroup(-1, new Quaterniond(), new Vector3d(), list)); + } + } + + private void solve(Collection result) { + Map axisGroup = this.groupByAxis(); + List moduloGroup = this.groupByModulo(axisGroup); + Map> planeGroup = this.combineGroup(moduloGroup); + this.fixGroups(result, planeGroup); + } + + private void simpleConvert(Collection result, List moduloGroup) { + for (PlaneGroup plane : moduloGroup) { + ArrayList list = new ArrayList<>(); + this.rotateCubes(list, plane.cubes(), plane.invOrigin()); + result.add(new ItemGroup(0, new Quaterniond(plane.origin()), TMath.toEulerXYZ(plane.origin()), list)); + } + } + + private List toAxes(int cubeId) { + ProcessedBone.Cube cube = (ProcessedBone.Cube)this.cubes.get(cubeId); + Vector3d px = TMath.fixVector(new HashedVector3d(Axis.X, 1.0, 0.0, 0.0).rotate(cube.getQuaternion())); + Vector3d py = TMath.fixVector(new HashedVector3d(Axis.Y, 0.0, 1.0, 0.0).rotate(cube.getQuaternion())); + Vector3d pz = TMath.fixVector(new HashedVector3d(Axis.Z, 0.0, 0.0, 1.0).rotate(cube.getQuaternion())); + return Arrays.asList(px, py, pz); + } + + private Map groupByAxis() { + Object2ObjectLinkedOpenHashMap map = new Object2ObjectLinkedOpenHashMap(); + IntIterator var2 = this.cubes.keySet().iterator(); + + while (var2.hasNext()) { + int key = (Integer)var2.next(); + List axes = this.toAxes(key); + this.axes.put(key, axes); + + for (Vector3d axis : axes) { + ((IntLinkedOpenHashSet)map.computeIfAbsent(axis, vector3d -> new IntLinkedOpenHashSet())).add(key); + } + } + + return fetch(map); + } + + private List groupByModulo(Map byAxis) { + Object2ObjectLinkedOpenHashMap> temp = new Object2ObjectLinkedOpenHashMap(); + ArrayList result = new ArrayList<>(); + + for (Entry entry : byAxis.entrySet()) { + Quaterniond toOrigin = null; + IntListIterator subGroup = entry.getValue().iterator(); + + while (subGroup.hasNext()) { + int cubeId = (Integer)subGroup.next(); + ProcessedBone.Cube cube = (ProcessedBone.Cube)this.cubes.get(cubeId); + double angle; + if (toOrigin == null) { + toOrigin = cube.getQuaternion().invert(new Quaterniond()); + angle = 0.0; + } else { + Quaterniond localQ = toOrigin.mul(cube.getQuaternion(), new Quaterniond()); + Vector3d lqVec = new Vector3d(localQ.x, localQ.y, localQ.z); + double sign = Math.signum(lqVec.dot((Vector3dc)entry.getKey())); + angle = sign * 2.0 * Math.acos(localQ.w) * (180.0 / Math.PI); + } + + int groupId = getGroupId(angle); + ((IntSet)((Int2ObjectMap)temp.computeIfAbsent(entry.getKey(), vector3d -> new Int2ObjectLinkedOpenHashMap())) + .computeIfAbsent(groupId, integer -> new IntLinkedOpenHashSet())) + .add(cubeId); + } + } + + ObjectBidirectionalIterator var16 = temp.entrySet().iterator(); + + while (var16.hasNext()) { + Entry> group = (Entry>)var16.next(); + ObjectIterator var18 = group.getValue().int2ObjectEntrySet().iterator(); + + while (var18.hasNext()) { + it.unimi.dsi.fastutil.ints.Int2ObjectMap.Entry subGroup = (it.unimi.dsi.fastutil.ints.Int2ObjectMap.Entry)var18.next(); + int firstCubeId = ((IntSet)subGroup.getValue()).iterator().nextInt(); + Quaterniond rotation = ((ProcessedBone.Cube)this.cubes.get(firstCubeId)).getQuaternion(); + result.add( + new PlaneGroup( + new Vector3d((Vector3dc)group.getKey()), + subGroup.getIntKey(), + new Quaterniond(rotation), + rotation.invert(new Quaterniond()), + (IntSet)subGroup.getValue() + ) + ); + } + } + + return result; + } + + private Map> combineGroup(List planes) { + Object2ObjectLinkedOpenHashMap> map = new Object2ObjectLinkedOpenHashMap(); + + for (int a = 0; a < planes.size(); a++) { + PlaneGroup groupA = planes.get(a); + Set set = (Set)map.computeIfAbsent(groupA, planeGroup -> new ObjectLinkedOpenHashSet()); + set.add(groupA); + + label55: + for (int b = a + 1; b < planes.size(); b++) { + PlaneGroup groupB = planes.get(b); + if (TMath.isSimilar(groupA.axis().dot(groupB.axis()), -1.0)) { + List axesA = (List)this.axes.get(groupA.cubes().iterator().nextInt()); + List axesB = (List)this.axes.get(groupB.cubes().iterator().nextInt()); + + for (int i = 0; i < 3; i++) { + Vector3d axisA = axesA.get(i); + Vector3d axisB = axesB.get(i); + if (getGroupId(Math.acos(axisA.dot(axisB)) * (180.0 / Math.PI)) != 0) { + continue label55; + } + } + } else { + for (PlaneGroup g : set) { + double dot = g.axis().dot(groupB.axis()); + if (!TMath.isSimilar(dot, 0.0) && !TMath.isSimilar(dot, -1.0)) { + continue label55; + } + + Vector3d vA = groupB.axis().rotate(g.invOrigin(), new Vector3d()); + Vector3d vB = g.axis().rotate(groupB.invOrigin(), new Vector3d()); + if (!isGroupable(vA) || !isGroupable(vB)) { + continue label55; + } + } + } + + set.add(groupB); + } + } + + return fetch(map); + } + + private void fixGroups(Collection result, Map> planeGroupMap) { + for (Entry> entry : planeGroupMap.entrySet()) { + Set planeGroups = entry.getValue(); + if (planeGroups.size() < 2) { + PlaneGroup group = planeGroups.iterator().next(); + result.add( + new ItemGroup( + 0, new Quaterniond(group.origin()), TMath.toEulerXYZ(group.origin()), this.rotateCubes(new ArrayList<>(), group.cubes(), group.invOrigin()) + ) + ); + } else { + Iterator iterator = planeGroups.iterator(); + PlaneGroup groupA = iterator.next(); + Vector3d axisA = groupA.axis(); + Vector3d axisB = iterator.next().axis(); + + while (TMath.isSimilar(Math.abs(axisA.dot(axisB)), 1.0) && iterator.hasNext()) { + axisB = iterator.next().axis(); + } + + if (TMath.isSimilar(Math.abs(axisA.dot(axisB)), 1.0)) { + ArrayList list = new ArrayList<>(); + + for (PlaneGroup planeGroup : planeGroups) { + this.rotateCubes(list, planeGroup.cubes(), groupA.invOrigin()); + } + + result.add(new ItemGroup(0, new Quaterniond(groupA.origin()), TMath.toEulerXYZ(groupA.origin()), list)); + } else { + Vector3d cardinalA = getClosestCardinal(axisA); + Quaterniond aToCardinal = axisA.rotationTo(cardinalA, new Quaterniond()); + Vector3d axisBPrime = axisB.rotate(aToCardinal, new Vector3d()); + Vector3d cardinalB = getClosestCardinal(axisBPrime); + Quaterniond bPrimeToCardinal = axisBPrime.rotationTo(cardinalB, new Quaterniond()); + Quaterniond invRoot = bPrimeToCardinal.mul(aToCardinal); + Quaterniond rootRotation = invRoot.invert(new Quaterniond()); + Vector3d rootEuler = TMath.fixEuler(TMath.toEulerXYZ(rootRotation)); + ArrayList list = new ArrayList<>(); + + for (PlaneGroup planeGroup : planeGroups) { + this.rotateCubes(list, planeGroup.cubes(), invRoot); + } + + result.add(new ItemGroup(1, rootRotation, rootEuler, list)); + } + } + } + } + + private List rotateCubes(List result, IntSet cubeIds, Quaterniond quaterniond) { + IntIterator var4 = cubeIds.iterator(); + + while (var4.hasNext()) { + int cubeId = (Integer)var4.next(); + ProcessedBone.Cube cube = (ProcessedBone.Cube)this.cubes.get(cubeId); + cube.rotate(quaterniond); + result.add(IllegalRotationSolver.solve(cube)); + } + + return result; + } + + private static , S> Map fetch(Map map) { + PriorityQueue> queue = new PriorityQueue<>(Comparator., Integer>comparing(pair -> ((Collection)pair.second()).size()).reversed()); + map.forEach((t, rs) -> queue.add(Pair.of(t, rs))); + Object2ObjectLinkedOpenHashMap result = new Object2ObjectLinkedOpenHashMap(); + + while (!queue.isEmpty()) { + Pair largest = queue.poll(); + if (((Collection)largest.second()).isEmpty()) { + break; + } + + queue.clear(); + map.remove(largest.first()); + result.put(largest.first(), largest.second()); + map.forEach((t, rs) -> { + rs.removeAll((Collection)largest.second()); + queue.add(Pair.of(t, rs)); + }); + } + + return result; + } + + private static int getGroupId(double angle) { + while (angle < 0.0) { + angle += 360.0; + } + + int intAngle = (int)Math.round(angle * 10000.0); + return intAngle % 225000; + } + + private static boolean isGroupable(Vector3d vec) { + for (Axis axis : Axis.values()) { + if (getGroupId(Math.acos(vec.dot(axis.getVector())) * (float) (180.0 / Math.PI)) != 0) { + return false; + } + } + + return true; + } + + private static Vector3d getClosestCardinal(Vector3d vec) { + double dot = -1.0; + Vector3d cardinal = null; + + for (Vector3d axis : CARDINAL_AXES) { + double d = vec.dot(axis); + if (d > dot) { + dot = d; + cardinal = axis; + } + } + + return cardinal; + } + + private static boolean isLegal(ProcessedBone.Cube cube) { + return legalId(cube.getRotation().x) + legalId(cube.getRotation().y) + legalId(cube.getRotation().z) < 2; + } + + private static int legalId(double angle) { + if (TMath.isInterval(angle, 90.0)) { + return 0; + } else { + return TMath.isInterval(angle, 22.5) ? 1 : 999; + } + } + + private RotationSolver() { + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/javasupport/Java21Access.java b/core/src/main/java/com/ticxo/modelengine/core/javasupport/Java21Access.java new file mode 100644 index 0000000..821a5fa --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/javasupport/Java21Access.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.core.javasupport; + +import com.ticxo.modelengine.api.utils.CompatibilityManager; +import com.ticxo.modelengine.api.utils.MiscUtils; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.core.ModelEngine; + +public enum Java21Access implements ReflectionUtils.MethodEnum { + registerCompatibility(CompatibilityManager.class, ModelEngine.class), + createNMSHandler(String.class), + getMythicPackModelFiles(); + + private static Class HELPER; + private final Class[] parameterClasses; + + private static Class getHelper() { + if (!MiscUtils.isJavaVersionOrHigher(21)) { + throw new RuntimeException("Cannot get Java 21 Helper: Server is not using Java 21+!"); + } else { + if (HELPER == null) { + try { + HELPER = Class.forName("com.ticxo.modelengine.core21.Java21Helper"); + } catch (ClassNotFoundException var1) { + throw new RuntimeException(var1); + } + } + + return HELPER; + } + } + + private Java21Access(Class... parameterClasses) { + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return getHelper(); + } + + @Override + public String getObfuscated() { + return this.toString(); + } + + @Override + public String getMapped() { + return this.toString(); + } + + public T call(Object... parameters) { + return !MiscUtils.isJavaVersionOrHigher(21) ? null : ReflectionUtils.call(null, this, parameters); + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/javasupport/Java25Access.java b/core/src/main/java/com/ticxo/modelengine/core/javasupport/Java25Access.java new file mode 100644 index 0000000..c608783 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/javasupport/Java25Access.java @@ -0,0 +1,55 @@ +package com.ticxo.modelengine.core.javasupport; + +import com.ticxo.modelengine.api.utils.MiscUtils; +import com.ticxo.modelengine.api.utils.ReflectionUtils; + +public enum Java25Access implements ReflectionUtils.MethodEnum { + createNMSHandler(String.class); + + private static Class HELPER; + private final Class[] parameterClasses; + + private static Class getHelper() { + if (!MiscUtils.isJavaVersionOrHigher(25)) { + throw new RuntimeException("Cannot get Java 25 Helper: Server is not using Java 25+!"); + } else { + if (HELPER == null) { + try { + HELPER = Class.forName("com.ticxo.modelengine.core25.Java25Helper"); + } catch (ClassNotFoundException var1) { + throw new RuntimeException(var1); + } + } + + return HELPER; + } + } + + private Java25Access(Class... parameterClasses) { + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return getHelper(); + } + + @Override + public String getObfuscated() { + return this.toString(); + } + + @Override + public String getMapped() { + return this.toString(); + } + + public T call(Object... parameters) { + return !MiscUtils.isJavaVersionOrHigher(25) ? null : ReflectionUtils.call(null, this, parameters); + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/libsdisguises/DisguiseCompatibility.java b/core/src/main/java/com/ticxo/modelengine/core/libsdisguises/DisguiseCompatibility.java new file mode 100644 index 0000000..c6fed3f --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/libsdisguises/DisguiseCompatibility.java @@ -0,0 +1,32 @@ +package com.ticxo.modelengine.core.libsdisguises; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import me.libraryaddict.disguise.events.DisguiseEvent; +import me.libraryaddict.disguise.events.UndisguiseEvent; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +public class DisguiseCompatibility implements Listener { + private final Map disguiseToEntity = new HashMap<>(); + + @EventHandler( + priority = EventPriority.MONITOR + ) + public void onDisguise(DisguiseEvent event) { + this.disguiseToEntity.put(event.getDisguise().getUUID(), event.getDisguised().getUniqueId()); + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + public void onUndisguise(UndisguiseEvent event) { + this.disguiseToEntity.remove(event.getDisguise().getUUID()); + } + + public UUID getRelayOrDefault(UUID uuid) { + return this.disguiseToEntity.getOrDefault(uuid, uuid); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/listener/ChatListener.java b/core/src/main/java/com/ticxo/modelengine/core/listener/ChatListener.java new file mode 100644 index 0000000..f7d7f27 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/listener/ChatListener.java @@ -0,0 +1,31 @@ +package com.ticxo.modelengine.core.listener; + +import com.google.common.collect.Maps; +import io.papermc.paper.event.player.AsyncChatEvent; +import java.util.Map; +import java.util.UUID; +import java.util.function.Predicate; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class ChatListener implements Listener { + private static final Map> FETCH_MAP = Maps.newConcurrentMap(); + + @EventHandler + public void onAsyncChat(AsyncChatEvent event) { + UUID uuid = event.getPlayer().getUniqueId(); + Predicate fetch = FETCH_MAP.get(uuid); + if (fetch != null) { + event.setCancelled(true); + if (fetch.test(PlainTextComponentSerializer.plainText().serialize(event.message()))) { + FETCH_MAP.remove(uuid); + } + } + } + + public static void fetch(Player player, Predicate consumer) { + FETCH_MAP.put(player.getUniqueId(), consumer); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/listener/EntityListener.java b/core/src/main/java/com/ticxo/modelengine/core/listener/EntityListener.java new file mode 100644 index 0000000..b8c19fd --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/listener/EntityListener.java @@ -0,0 +1,119 @@ +package com.ticxo.modelengine.core.listener; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.core.menu.SelectionManager; +import com.ticxo.modelengine.core.menu.screen.NavigationScreen; +import it.unimi.dsi.fastutil.Pair; +import java.util.Optional; +import net.kyori.adventure.text.Component; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.event.entity.EntityPortalEvent; +import org.bukkit.event.entity.EntityTeleportEvent; +import org.bukkit.event.entity.ProjectileHitEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; + +public class EntityListener implements Listener { + @EventHandler( + priority = EventPriority.MONITOR + ) + public void onEntityDamage(EntityDamageEvent event) { + if (!event.isCancelled()) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(event.getEntity()); + if (model != null) { + model.markHurt(); + } + } + } + + @EventHandler + public void onEntityAttacked(EntityDamageByEntityEvent event) { + if (event.getDamager() instanceof Player player && SelectionManager.isSelecting(player)) { + Entity target = event.getEntity(); + event.setCancelled(true); + SelectionManager.setSelecting(player, false); + SelectionManager.setSelected(player, target); + player.sendActionBar(Component.text("Selected " + target.getName() + ".")); + new NavigationScreen(player).openScreen(); + } else { + Pair pair = ModelEngineAPI.getMountPairManager().get(event.getDamager().getUniqueId()); + if (pair != null) { + Object base = ((ActiveModel)pair.left()).getModeledEntity().getBase().getOriginal(); + MountController controller = (MountController)pair.right(); + if (base.equals(event.getEntity()) && !controller.canDamageMount()) { + event.setCancelled(true); + } + } + } + } + + @EventHandler + public void onEntityInteracted(PlayerInteractEntityEvent event) { + Pair pair = ModelEngineAPI.getMountPairManager().get(event.getPlayer().getUniqueId()); + if (pair != null) { + Object base = ((ActiveModel)pair.left()).getModeledEntity().getBase().getOriginal(); + MountController controller = (MountController)pair.right(); + if (base.equals(event.getRightClicked()) && !controller.canInteractMount()) { + event.setCancelled(true); + } + } + } + + @EventHandler + public void onProjectileHit(ProjectileHitEvent event) { + if (event.getEntity().getShooter() instanceof Entity entity && event.getHitEntity() != null) { + Pair pair = ModelEngineAPI.getMountPairManager().get(entity.getUniqueId()); + if (pair == null) { + return; + } + + Object base = ((ActiveModel)pair.left()).getModeledEntity().getBase().getOriginal(); + MountController controller = (MountController)pair.right(); + if (base.equals(event.getHitEntity()) && !controller.canDamageMount()) { + event.setCancelled(true); + } + } + } + + @EventHandler + public void onPortal(EntityPortalEvent event) { + Entity entity = event.getEntity(); + if (ModelEngineAPI.getMountPairManager().get(entity.getUniqueId()) != null) { + event.setCancelled(true); + } else { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(entity); + if (modeledEntity != null) { + for (ActiveModel model : modeledEntity.getModels().values()) { + Optional manager = model.getMountManager(); + if (!manager.isEmpty() && ((MountManager)((BehaviorManager)manager.get())).hasPassengers()) { + event.setCancelled(true); + return; + } + } + } + } + } + + @EventHandler + public void onTeleport(EntityTeleportEvent event) { + if (!(event instanceof EntityPortalEvent)) { + ModelEngineAPI.getMountPairManager().tryDismount(event.getEntity()); + } + } + + @EventHandler + public void onDeath(EntityDeathEvent event) { + ModelEngineAPI.getMountPairManager().tryDismount(event.getEntity()); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/listener/InventoryListener.java b/core/src/main/java/com/ticxo/modelengine/core/listener/InventoryListener.java new file mode 100644 index 0000000..b6ebaa8 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/listener/InventoryListener.java @@ -0,0 +1,46 @@ +package com.ticxo.modelengine.core.listener; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.menu.ScreenManager; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.inventory.Inventory; + +public class InventoryListener implements Listener { + @EventHandler + public void onInventoryClick(InventoryClickEvent event) { + if (!event.isCancelled()) { + Inventory inventory = event.getInventory(); + AbstractScreen screen = this.getScreenManager().getScreen(inventory); + if (screen != null && event.getWhoClicked() instanceof Player player) { + if (event.getClickedInventory() == inventory) { + event.setCancelled(true); + screen.onClick(player, event.getSlot(), event); + } else { + screen.onClickPlayer(player, event.getSlot(), event); + } + } + } + } + + @EventHandler + public void onInventoryDrag(InventoryDragEvent event) { + if (this.getScreenManager().isScreen(event.getInventory())) { + event.setCancelled(true); + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + this.getScreenManager().unregisterScreen(event.getInventory()); + } + + private ScreenManager getScreenManager() { + return ModelEngineAPI.getAPI().getScreenManager(); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/listener/PlayerListener.java b/core/src/main/java/com/ticxo/modelengine/core/listener/PlayerListener.java new file mode 100644 index 0000000..ddaaf7b --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/listener/PlayerListener.java @@ -0,0 +1,119 @@ +package com.ticxo.modelengine.core.listener; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BukkitPlayer; +import com.ticxo.modelengine.api.entity.cull.BasicCulling; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.core.menu.SelectionManager; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerPortalEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRegisterChannelEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.PlayerUnregisterChannelEvent; +import org.bukkit.util.Vector; + +public class PlayerListener implements Listener { + @EventHandler + public void onJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + ServerInfo.setOnline(player.getUniqueId(), true); + ModelEngineAPI.getNetworkHandler().injectChannel(player); + AnimationLODHandler.registerPlayer(player.getUniqueId()); + if (ModelEngineAPI.getConfigCache().isEagerGenerate()) { + ModelEngineAPI.getUserLimbRegistry().generate(player); + } + } + + @EventHandler + public void onQuit(PlayerQuitEvent event) { + Player player = event.getPlayer(); + ServerInfo.setOnline(player.getUniqueId(), false); + ModelEngineAPI.getNetworkHandler().ejectChannel(player); + ModelEngineAPI.getMountPairManager().tryDismount(player); + ModelEngineAPI.getInteractionTracker().removeDynamicHitbox(player.getUniqueId()); + ModelEngineAPI.getEntityHandler().setForcedInvisible(player, false); + SelectionManager.removePlayer(event.getPlayer()); + AnimationLODHandler.setPlayerActive(event.getPlayer().getUniqueId(), false); + BasicCulling.setGlobalCullExempt(player.getUniqueId(), false); + ModelEngineAPI.getPivotOverrideRegistry().remove(player.getUniqueId()); + ModPlayerTracker.removePlayer(player.getUniqueId()); + } + + @EventHandler + public void onChannelRegister(PlayerRegisterChannelEvent event) { + if ("modelengine:bulk_data".equals(event.getChannel())) { + ModPlayerTracker.addPlayer(event.getPlayer().getUniqueId()); + } + } + + @EventHandler + public void onChannelUnregister(PlayerUnregisterChannelEvent event) { + if ("modelengine:bulk_data".equals(event.getChannel())) { + ModPlayerTracker.removePlayer(event.getPlayer().getUniqueId()); + } + } + + @EventHandler + public void onPortal(PlayerPortalEvent event) { + Player entity = event.getPlayer(); + if (ModelEngineAPI.getMountPairManager().get(entity.getUniqueId()) != null) { + event.setCancelled(true); + } + } + + @EventHandler + public void onTeleport(PlayerTeleportEvent event) { + if (!(event instanceof PlayerPortalEvent)) { + ModelEngineAPI.getMountPairManager().tryDismount(event.getPlayer()); + } + } + + @EventHandler + public void onChangedWorld(PlayerChangedWorldEvent event) { + Player player = event.getPlayer(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(player.getUniqueId()); + if (modeledEntity != null) { + if (modeledEntity.getBase().getData() instanceof BukkitEntityData data) { + data.resendTracking(player.getUniqueId()); + } + + ModelEngineAPI.getPivotOverrideRegistry().get(player.getUniqueId()).ifPresent(override -> override.getPassengers().markDirty()); + } + } + + @EventHandler + public void onDeath(PlayerDeathEvent event) { + ModelEngineAPI.getMountPairManager().tryDismount(event.getPlayer()); + } + + @EventHandler + public void onMove(PlayerMoveEvent event) { + Vector dir = event.getTo().toVector().subtract(event.getFrom().toVector()); + if (!dir.isZero()) { + Player player = event.getPlayer(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(player.getUniqueId()); + if (modeledEntity != null) { + if (modeledEntity.getBase().getData() instanceof BukkitPlayer.BukkitPlayerData playerData) { + if (dir.getX() != 0.0 || dir.getZ() != 0.0) { + playerData.setWalkTick(3); + } + + if (dir.getY() > 0.0) { + playerData.setJumpTick(3); + } + } + } + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/listener/WorldListener.java b/core/src/main/java/com/ticxo/modelengine/core/listener/WorldListener.java new file mode 100644 index 0000000..b3c46c5 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/listener/WorldListener.java @@ -0,0 +1,195 @@ +package com.ticxo.modelengine.core.listener; + +import com.google.gson.JsonSyntaxException; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.generator.ModelGenerator; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import com.ticxo.modelengine.api.utils.ticker.DualTicker; +import com.ticxo.modelengine.core.data.DataUpdater; +import java.util.ArrayList; +import java.util.List; +import net.citizensnpcs.api.CitizensAPI; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.world.EntitiesLoadEvent; +import org.bukkit.event.world.EntitiesUnloadEvent; +import org.bukkit.event.world.WorldLoadEvent; +import org.bukkit.event.world.WorldUnloadEvent; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataType; + +public class WorldListener implements Listener { + private static final int PHANTOM_UNLOAD_RECHECK_TICKS = 5; + private final ModelGenerator generator; + private boolean onWorldLoad = false; + private boolean onWorldUnload = false; + + public WorldListener() { + this.generator = ModelEngineAPI.getAPI().getModelGenerator(); + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> { + this.onWorldLoad = ConfigProperty.LOAD_ON_WORLD_LOAD.getBoolean(); + this.onWorldUnload = ConfigProperty.UNLOAD_ON_WORLD_UNLOAD.getBoolean(); + }); + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + private void onWorldLoad(WorldLoadEvent event) { + if (this.onWorldLoad) { + if (this.generator.isInitialized()) { + this.loadEntities(event.getWorld().getEntities()); + } else { + this.generator.queueTask(ModelGenerator.Phase.POST_IMPORT, () -> DualTicker.queueSyncTask(() -> this.loadEntities(event.getWorld().getEntities()))); + } + } + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + private void onWorldUnload(WorldUnloadEvent event) { + if (this.onWorldUnload) { + if (this.generator.isInitialized()) { + this.unloadEntities(event.getWorld().getEntities()); + } else { + this.generator + .queueTask(ModelGenerator.Phase.POST_IMPORT, () -> DualTicker.queueSyncTask(() -> this.unloadEntities(event.getWorld().getEntities()))); + } + } + } + + @EventHandler( + priority = EventPriority.LOWEST + ) + private void onEntityLoad(EntitiesLoadEvent event) { + if (!this.onWorldLoad) { + if (this.generator.isInitialized()) { + this.loadEntities(event.getEntities()); + } else { + this.generator.queueTask(ModelGenerator.Phase.POST_IMPORT, () -> DualTicker.queueSyncTask(() -> this.loadEntities(event.getEntities()))); + } + } + } + + @EventHandler( + priority = EventPriority.MONITOR + ) + private void onEntityUnload(EntitiesUnloadEvent event) { + if (!this.onWorldUnload) { + if (this.generator.isInitialized()) { + this.unloadEntities(event.getEntities()); + } else { + this.generator.queueTask(ModelGenerator.Phase.POST_IMPORT, () -> DualTicker.queueSyncTask(() -> this.unloadEntities(event.getEntities()))); + } + } + } + + private void loadEntities(List entities) { + for (Entity entity : entities) { + if (!(entity instanceof Player) && !ServerInfo.scheduleOnRegion(entity, () -> this.restoreSavedModel(entity))) { + this.restoreSavedModel(entity); + } + } + } + + private void restoreSavedModel(Entity entity) { + if (ModelEngineAPI.getModeledEntity(entity.getUniqueId()) == null) { + String jsonData = (String)entity.getPersistentDataContainer().get(SavedData.DATA_KEY, PersistentDataType.STRING); + if (jsonData != null) { + try { + SavedData data = DataUpdater.convertToSavedData(entity.getLocation(), jsonData); + if (!DataUpdater.tryUpdate(data)) { + return; + } + + ModeledEntity model = ModelEngineAPI.createModeledEntity(entity); + model.load(data); + } catch (JsonSyntaxException var5) { + var5.printStackTrace(); + } + } + } + } + + private void unloadEntities(List entities) { + List unloaded = null; + + for (Entity entity : entities) { + if (!(entity instanceof Player) && (!ServerInfo.HAS_CITIZENS || !CitizensAPI.getNPCRegistry().isNPC(entity))) { + PersistentDataContainer pdc = entity.getPersistentDataContainer(); + ModeledEntity model = ModelEngineAPI.getModeledEntity(entity.getUniqueId()); + if (model == null) { + pdc.remove(SavedData.DATA_KEY); + } else { + if (model.shouldBeSaved()) { + try { + String cachedJson = model.getCachedSaveJson(); + if (cachedJson != null) { + pdc.set(SavedData.DATA_KEY, PersistentDataType.STRING, cachedJson); + } else { + model.save() + .ifPresentOrElse( + data -> pdc.set(SavedData.DATA_KEY, PersistentDataType.STRING, data.toString()), () -> pdc.remove(SavedData.DATA_KEY) + ); + } + } catch (Throwable var8) { + throw new IllegalStateException( + "Failed to save data for entity " + + entity.getType() + + " " + + entity.getUniqueId() + + " at " + + entity.getLocation().getX() + + "," + + entity.getLocation().getY() + + "," + + entity.getLocation().getZ(), + var8 + ); + } + } else { + entity.getPersistentDataContainer().remove(SavedData.DATA_KEY); + } + + ModelEngineAPI.getEntityHandler().setForcedInvisible(entity, false); + ModelEngineAPI.getAPI().getModelUpdaters().forceRemoveModeledEntity(model); + if (model.shouldBeSaved()) { + if (unloaded == null) { + unloaded = new ArrayList<>(); + } + + unloaded.add(entity); + } + } + } + } + + if (unloaded != null) { + List recheck = unloaded; + if (ServerInfo.IS_FOLIA) { + for (Entity entityx : recheck) { + ServerInfo.scheduleOnRegionDelayed(entityx, () -> { + if (entityx.isValid()) { + this.restoreSavedModel(entityx); + } + }, 5L); + } + } else { + DualTicker.queueDelayedSyncTask(() -> { + for (Entity entityx : recheck) { + if (entityx.isValid()) { + this.restoreSavedModel(entityx); + } + } + }, 5); + } + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/SelectionManager.java b/core/src/main/java/com/ticxo/modelengine/core/menu/SelectionManager.java new file mode 100644 index 0000000..8e620bd --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/SelectionManager.java @@ -0,0 +1,44 @@ +package com.ticxo.modelengine.core.menu; + +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; + +public class SelectionManager { + private static final Set SELECTING = Sets.newConcurrentHashSet(); + private static final Map SELECTED = Maps.newConcurrentMap(); + + public static void setSelecting(Player player, boolean flag) { + if (flag) { + SELECTING.add(player.getUniqueId()); + } else { + SELECTING.remove(player.getUniqueId()); + } + } + + public static boolean isSelecting(Player player) { + return SELECTING.contains(player.getUniqueId()); + } + + public static void setSelected(Player player, @Nullable Entity entity) { + if (entity == null) { + SELECTED.remove(player.getUniqueId()); + } else { + SELECTED.put(player.getUniqueId(), entity); + } + } + + public static Entity getSelected(Player player) { + return SELECTED.get(player.getUniqueId()); + } + + public static void removePlayer(Player player) { + SELECTING.remove(player.getUniqueId()); + SELECTED.remove(player.getUniqueId()); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/screen/AddModelScreen.java b/core/src/main/java/com/ticxo/modelengine/core/menu/screen/AddModelScreen.java new file mode 100644 index 0000000..04ea01c --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/screen/AddModelScreen.java @@ -0,0 +1,76 @@ +package com.ticxo.modelengine.core.menu.screen; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelRegistry; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.utils.data.ComponentUtil; +import com.ticxo.modelengine.api.utils.data.ItemUtils; +import com.ticxo.modelengine.core.menu.widget.BasicItemWidget; +import com.ticxo.modelengine.core.menu.widget.BorderWidget; +import com.ticxo.modelengine.core.menu.widget.CloseWidget; +import com.ticxo.modelengine.core.menu.widget.PaginatorWidget; +import com.ticxo.modelengine.core.menu.widget.page.AbstractModelButton; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class AddModelScreen extends AbstractScreen { + private final Entity selected; + private final PaginatorWidget page; + + public AddModelScreen(AbstractScreen rootScreen, Player viewer, Entity selected) { + super(viewer, "Add Model", 6); + this.selected = selected; + this.addWidget(new BorderWidget()); + this.page = new PaginatorWidget(); + this.addWidget(this.page); + ModelRegistry registry = ModelEngineAPI.getAPI().getModelRegistry(); + ItemStack statSign = new ItemStack(Material.OAK_SIGN); + ItemUtils.name(statSign, Component.text("Stats", ComponentUtil.reset().decoration(TextDecoration.BOLD, true))); + ItemUtils.lore(statSign, Component.empty(), Component.text("Models: " + registry.getKeys().size(), ComponentUtil.reset())); + this.addWidget(new BasicItemWidget(53, statSign)); + this.addWidget(new CloseWidget(rootScreen)); + } + + @Override + public void openScreen() { + this.updatePage(); + super.openScreen(); + } + + private void updatePage() { + this.page.clearButtons(); + ModelRegistry registry = ModelEngineAPI.getAPI().getModelRegistry(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.selected); + + for (String modelId : registry.getOrderedId()) { + if (modeledEntity == null || !modeledEntity.getModel(modelId).isPresent()) { + ModelBlueprint blueprint = registry.get(modelId); + AddModelScreen.ModelButton button = new AddModelScreen.ModelButton(blueprint); + this.page.addButton(button); + } + } + } + + class ModelButton extends AbstractModelButton { + public ModelButton(ModelBlueprint blueprint) { + super(blueprint); + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + ModeledEntity modeledEntity = ModelEngineAPI.getOrCreateModeledEntity(AddModelScreen.this.selected, me -> me.setBaseEntityVisible(false)); + ActiveModel activeModel = ModelEngineAPI.createActiveModel(this.blueprint); + modeledEntity.addModel(activeModel, true).ifPresent(ActiveModel::destroy); + AddModelScreen.this.updatePage(); + AddModelScreen.this.draw(true); + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/screen/EditEntityScreen.java b/core/src/main/java/com/ticxo/modelengine/core/menu/screen/EditEntityScreen.java new file mode 100644 index 0000000..ef60178 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/screen/EditEntityScreen.java @@ -0,0 +1,372 @@ +package com.ticxo.modelengine.core.menu.screen; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.menu.Widget; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.utils.MiscUtils; +import com.ticxo.modelengine.api.utils.data.ComponentUtil; +import com.ticxo.modelengine.api.utils.data.ItemUtils; +import com.ticxo.modelengine.api.utils.ticker.DualTicker; +import com.ticxo.modelengine.core.listener.ChatListener; +import com.ticxo.modelengine.core.menu.widget.BorderWidget; +import com.ticxo.modelengine.core.menu.widget.CloseWidget; +import com.ticxo.modelengine.core.menu.widget.PaginatorWidget; +import com.ticxo.modelengine.core.menu.widget.TabWidget; +import com.ticxo.modelengine.core.menu.widget.page.AbstractModelButton; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +public class EditEntityScreen extends AbstractScreen { + private final Entity selected; + private final TabWidget tab; + + public EditEntityScreen(AbstractScreen rootScreen, Player viewer, @NotNull Entity selected) { + super(viewer, "Editing: " + selected.getName(), 6); + this.selected = selected; + this.addWidget(new BorderWidget()); + this.tab = new TabWidget(); + this.tab.addTab(new EditEntityScreen.SettingsTab()); + this.tab.addTab(new EditEntityScreen.ModelTab()); + this.addWidget(this.tab); + this.addWidget(new EditEntityScreen.EntityStatsWidget()); + this.addWidget(new CloseWidget(rootScreen)); + } + + @Override + public void openScreen() { + if (this.tab.getSelectedTab() instanceof EditEntityScreen.ModelTab modelTab) { + modelTab.updatePage(); + } + + super.openScreen(); + } + + class EntityStatsWidget implements Widget { + private static final int SLOT = 53; + private final ItemStack stack = new ItemStack(Material.OAK_SIGN); + + public EntityStatsWidget() { + this.updateStats(); + } + + @Override + public ItemStack getItemForSlot(int size, int slot) { + return slot == 53 ? this.stack : null; + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + if (slot == 53) { + if (event.isLeftClick()) { + this.updateStats(); + EditEntityScreen.this.markSlotDirty(53); + } else if (event.isRightClick()) { + player.teleport(EditEntityScreen.this.selected.getLocation()); + } + } + } + + private void updateStats() { + String location = EditEntityScreen.this.selected.getLocation().getBlockX() + + ", " + + EditEntityScreen.this.selected.getLocation().getBlockY() + + ", " + + EditEntityScreen.this.selected.getLocation().getBlockZ(); + ItemUtils.name(this.stack, Component.text("Stats", ComponentUtil.reset().decoration(TextDecoration.BOLD, true))); + ItemUtils.lore( + this.stack, + Component.empty(), + Component.text("Type: ", ComponentUtil.reset()).append(Component.translatable(EditEntityScreen.this.selected.getType().getTranslationKey())), + Component.text("UUID: " + EditEntityScreen.this.selected.getUniqueId(), ComponentUtil.reset()), + Component.text("Position: " + location, ComponentUtil.reset()), + Component.text("Status: " + (EditEntityScreen.this.selected.isDead() ? "Dead" : "Alive"), ComponentUtil.reset()), + Component.empty(), + Component.text("Left click to refresh stats.", ComponentUtil.color(NamedTextColor.DARK_GRAY)), + Component.text("Right click to teleport to entity.", ComponentUtil.color(NamedTextColor.DARK_GRAY)) + ); + } + } + + class ModelTab implements TabWidget.Tab { + private final ItemStack stack = new ItemStack(Material.ARMOR_STAND); + private final PaginatorWidget page; + + public ModelTab() { + ItemUtils.name(this.stack, Component.text("Models", ComponentUtil.reset())); + this.page = new PaginatorWidget(); + } + + @Override + public ItemStack getItemStack() { + return this.stack; + } + + @Override + public Widget getWidget() { + return this.page; + } + + @Override + public void onSelect() { + this.updatePage(); + } + + private void updatePage() { + this.page.clearButtons(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(EditEntityScreen.this.selected); + if (modeledEntity != null) { + for (ActiveModel model : modeledEntity.getModels().values()) { + EditEntityScreen.ModelTab.ModelButton button = new EditEntityScreen.ModelTab.ModelButton(model); + this.page.addButton(button); + } + } + + this.page.addButton(new EditEntityScreen.ModelTab.AddModelButton()); + } + + class AddModelButton implements PaginatorWidget.PageButton { + private final ItemStack stack = new ItemStack(Material.NETHER_STAR); + + public AddModelButton() { + ItemUtils.name(this.stack, Component.text("Add Model", ComponentUtil.reset())); + } + + @Override + public ItemStack getItemStack() { + return this.stack; + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + new AddModelScreen(screen, player, EditEntityScreen.this.selected).openScreen(); + } + } + + class ModelButton extends AbstractModelButton { + private final ActiveModel model; + + public ModelButton(ActiveModel model) { + super(model.getBlueprint()); + this.model = model; + } + + @Override + protected void updateItem() { + ItemUtils.name(this.stack, Component.text(this.blueprint.getName(), ComponentUtil.reset())); + ItemUtils.lore( + this.stack, + Component.empty(), + Component.text("Model ID: " + this.blueprint.getName(), ComponentUtil.reset()), + Component.text("Hitbox: " + this.blueprint.getMainHitbox().toSimpleString(), ComponentUtil.reset()), + Component.text("Eye Height: " + this.blueprint.getMainHitbox().toEyeHeightString(), ComponentUtil.reset()), + Component.text("Shadow: " + this.blueprint.getShadowRadius(), ComponentUtil.reset()), + Component.text("Bone Count: " + this.blueprint.getFlatMap().size(), ComponentUtil.reset()), + Component.empty(), + Component.text("Shift-click to remove model.", ComponentUtil.color(NamedTextColor.DARK_GRAY)) + ); + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + if (event.isShiftClick()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(EditEntityScreen.this.selected); + if (modeledEntity == null) { + return; + } + + modeledEntity.removeModel(this.model.getBlueprint().getName()).ifPresent(ActiveModel::destroy); + if (modeledEntity.getModels().isEmpty()) { + modeledEntity.setBaseEntityVisible(true); + ModelEngineAPI.removeModeledEntity(EditEntityScreen.this.selected); + } + + ModelTab.this.updatePage(); + EditEntityScreen.this.draw(true); + } else { + new EditModelScreen(screen, player, this.model).openScreen(); + } + } + } + } + + class SettingsTab implements TabWidget.Tab { + private final ItemStack stack = new ItemStack(Material.COMMAND_BLOCK); + private final EditEntityScreen.SettingsWidget widget; + + public SettingsTab() { + ItemUtils.name(this.stack, Component.text("Entity Settings", ComponentUtil.reset())); + this.widget = EditEntityScreen.this.new SettingsWidget(); + } + + @Override + public ItemStack getItemStack() { + return this.stack; + } + + @Override + public Widget getWidget() { + return this.widget; + } + + @Override + public void onSelect() { + } + } + + class SettingsWidget implements Widget { + private static final int VISIBLE_SLOT = 29; + private static final int SAVED_SLOT = 30; + private static final int ROT_LOCK_SLOT = 31; + private static final int RENDER_RADIUS_SLOT = 32; + private static final int STEP_HEIGHT_SLOT = 33; + private final ModeledEntity modeledEntity = ModelEngineAPI.getOrCreateModeledEntity(EditEntityScreen.this.selected, me -> me.setBaseEntityVisible(false)); + private final ItemStack visible = new ItemStack(Material.ENDER_EYE); + private final ItemStack saved; + private final ItemStack rotLock; + private final ItemStack renderRadius; + private final ItemStack stepHeight; + + public SettingsWidget() { + ItemUtils.name( + this.visible, + Component.text( + "Base Entity Visible: " + this.modeledEntity.isBaseEntityVisible(), + ComponentUtil.color(this.modeledEntity.isBaseEntityVisible() ? NamedTextColor.GREEN : NamedTextColor.RED) + ) + ); + ItemUtils.lore(this.visible, Component.empty(), Component.text("Is the actual entity visible.", ComponentUtil.reset())); + this.saved = new ItemStack(Material.CHEST); + ItemUtils.name( + this.saved, + Component.text( + "Model Persistent: " + this.modeledEntity.shouldBeSaved(), + ComponentUtil.color(this.modeledEntity.shouldBeSaved() ? NamedTextColor.GREEN : NamedTextColor.RED) + ) + ); + ItemUtils.lore(this.saved, Component.empty(), Component.text("Should the models be saved on unload.", ComponentUtil.reset())); + this.rotLock = new ItemStack(Material.COMPASS); + ItemUtils.name( + this.rotLock, + Component.text( + "Rotation Locked: " + this.modeledEntity.isModelRotationLocked(), + ComponentUtil.color(this.modeledEntity.isModelRotationLocked() ? NamedTextColor.GREEN : NamedTextColor.RED) + ) + ); + ItemUtils.lore(this.rotLock, Component.empty(), Component.text("Can the models rotate with the entity.", ComponentUtil.reset())); + this.renderRadius = new ItemStack(Material.SPYGLASS); + ItemUtils.name(this.renderRadius, Component.text("Render Radius: " + this.modeledEntity.getBase().getRenderRadius(), ComponentUtil.reset())); + ItemUtils.lore(this.renderRadius, Component.empty(), Component.text("The render radius of the entity in blocks.", ComponentUtil.reset())); + this.stepHeight = new ItemStack(Material.STONE_STAIRS); + ItemUtils.name( + this.stepHeight, + Component.text("Step Height: " + MiscUtils.FORMATTER.format(this.modeledEntity.getBase().getMaxStepHeight()), ComponentUtil.reset()) + ); + ItemUtils.lore(this.stepHeight, Component.empty(), Component.text("The step height of the entity in blocks.", ComponentUtil.reset())); + } + + @Override + public ItemStack getItemForSlot(int size, int slot) { + return switch (slot) { + case 29 -> this.visible; + case 30 -> this.saved; + case 31 -> this.rotLock; + case 32 -> this.renderRadius; + case 33 -> this.stepHeight; + default -> null; + }; + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + switch (slot) { + case 29: + this.modeledEntity.setBaseEntityVisible(!this.modeledEntity.isBaseEntityVisible()); + ItemUtils.name( + this.visible, + Component.text( + "Base Entity Visible: " + this.modeledEntity.isBaseEntityVisible(), + ComponentUtil.color(this.modeledEntity.isBaseEntityVisible() ? NamedTextColor.GREEN : NamedTextColor.RED) + ) + ); + screen.markSlotDirty(29); + break; + case 30: + this.modeledEntity.setSaved(!this.modeledEntity.shouldBeSaved()); + ItemUtils.name( + this.saved, + Component.text( + "Model Persistent: " + this.modeledEntity.shouldBeSaved(), + ComponentUtil.color(this.modeledEntity.shouldBeSaved() ? NamedTextColor.GREEN : NamedTextColor.RED) + ) + ); + screen.markSlotDirty(30); + break; + case 31: + this.modeledEntity.setModelRotationLocked(!this.modeledEntity.isModelRotationLocked()); + ItemUtils.name( + this.rotLock, + Component.text( + "Rotation Locked: " + this.modeledEntity.isModelRotationLocked(), + ComponentUtil.color(this.modeledEntity.isModelRotationLocked() ? NamedTextColor.GREEN : NamedTextColor.RED) + ) + ); + screen.markSlotDirty(31); + break; + case 32: + player.closeInventory(); + ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter render radius:", ComponentUtil.color(NamedTextColor.AQUA))); + ChatListener.fetch( + player, + s -> { + try { + this.modeledEntity.getBase().setRenderRadius(Integer.parseInt(s)); + ComponentUtil.sendMessage( + player, Component.text("[ModelEngine] Set render radius of model to " + s + ".", ComponentUtil.color(NamedTextColor.GREEN)) + ); + screen.markSlotDirty(32); + DualTicker.queueSyncTask(EditEntityScreen.this::openScreen); + return true; + } catch (NumberFormatException var5) { + ComponentUtil.sendMessage( + player, Component.text("[ModelEngine] \"" + s + "\" is not an integer. Try again.", ComponentUtil.color(NamedTextColor.RED)) + ); + return false; + } + } + ); + break; + case 33: + player.closeInventory(); + ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter step height:", ComponentUtil.color(NamedTextColor.AQUA))); + ChatListener.fetch( + player, + s -> { + try { + this.modeledEntity.getBase().setMaxStepHeight(Double.parseDouble(s)); + ComponentUtil.sendMessage( + player, Component.text("[ModelEngine] Set step height of model to " + s + ".", ComponentUtil.color(NamedTextColor.GREEN)) + ); + screen.markSlotDirty(33); + DualTicker.queueSyncTask(EditEntityScreen.this::openScreen); + return true; + } catch (NumberFormatException var5) { + ComponentUtil.sendMessage( + player, Component.text("[ModelEngine] \"" + s + "\" is not a number. Try again.", ComponentUtil.color(NamedTextColor.RED)) + ); + return false; + } + } + ); + } + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/screen/EditModelScreen.java b/core/src/main/java/com/ticxo/modelengine/core/menu/screen/EditModelScreen.java new file mode 100644 index 0000000..8c15b89 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/screen/EditModelScreen.java @@ -0,0 +1,683 @@ +package com.ticxo.modelengine.core.menu.screen; + +import com.ticxo.modelengine.api.animation.BlueprintAnimation; +import com.ticxo.modelengine.api.animation.handler.AnimationHandler; +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.animation.property.SimpleProperty; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.menu.Widget; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.utils.MiscUtils; +import com.ticxo.modelengine.api.utils.data.ComponentUtil; +import com.ticxo.modelengine.api.utils.data.ItemUtils; +import com.ticxo.modelengine.api.utils.ticker.DualTicker; +import com.ticxo.modelengine.core.animation.handler.StateMachineHandler; +import com.ticxo.modelengine.core.listener.ChatListener; +import com.ticxo.modelengine.core.menu.widget.BorderWidget; +import com.ticxo.modelengine.core.menu.widget.CloseWidget; +import com.ticxo.modelengine.core.menu.widget.CompositeWidget; +import com.ticxo.modelengine.core.menu.widget.PaginatorWidget; +import com.ticxo.modelengine.core.menu.widget.TabWidget; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.Style; +import net.kyori.adventure.text.format.TextColor; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; + +public class EditModelScreen extends AbstractScreen { + private final ActiveModel model; + private final TabWidget tab; + + public EditModelScreen(AbstractScreen rootScreen, Player viewer, ActiveModel model) { + super(viewer, model.getBlueprint().getName(), 6); + this.model = model; + this.addWidget(new BorderWidget()); + this.tab = new TabWidget(); + this.tab.addTab(new EditModelScreen.SettingsTab()); + this.tab.addTab(new EditModelScreen.BoneTab()); + this.tab.addTab(new EditModelScreen.AnimationTab()); + this.addWidget(this.tab); + this.addWidget(new CloseWidget(rootScreen)); + } + + @Override + public void onTick() { + if (this.tab.getSelectedTab() instanceof EditModelScreen.AnimationTab animationTab) { + animationTab.onTick(); + } + + super.onTick(); + } + + class AnimationTab implements TabWidget.Tab { + private final ItemStack stack = new ItemStack(Material.ARMOR_STAND); + private final CompositeWidget composite; + private final PaginatorWidget page; + private final EditModelScreen.AnimationTab.PriorityButton priority; + + public AnimationTab() { + ItemUtils.name(this.stack, Component.text("Animations", ComponentUtil.reset())); + this.page = new PaginatorWidget(); + if (EditModelScreen.this.model.getAnimationHandler() instanceof StateMachineHandler) { + this.priority = new EditModelScreen.AnimationTab.PriorityButton(); + this.composite = new CompositeWidget(this.page, this.priority); + } else { + this.priority = null; + this.composite = null; + } + } + + @Override + public ItemStack getItemStack() { + return this.stack; + } + + @Override + public Widget getWidget() { + return (Widget)(this.composite != null ? this.composite : this.page); + } + + @Override + public void onSelect() { + this.page.clearButtons(); + ModelBlueprint blueprint = EditModelScreen.this.model.getBlueprint(); + Map pairs = blueprint.getAnimations(); + + for (Entry entry : pairs.entrySet()) { + this.page.addButton(new EditModelScreen.AnimationTab.AnimationButton(entry.getValue())); + } + } + + protected void onTick() { + int i = 19; + + while (i <= 43) { + switch (i % 9) { + default: + if (this.page.getButton(i) instanceof EditModelScreen.AnimationTab.AnimationButton button && button.update(false)) { + EditModelScreen.this.markSlotDirty(i); + } + case 0: + case 8: + i++; + } + } + } + + class AnimationButton implements PaginatorWidget.PageButton { + private final BlueprintAnimation animation; + private ItemStack stack; + private IAnimationProperty trackedProperty; + private int lastHash; + + public AnimationButton(BlueprintAnimation animation) { + this.animation = animation; + this.update(true); + } + + @Override + public ItemStack getItemStack() { + return this.stack; + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + AnimationHandler handler = EditModelScreen.this.model.getAnimationHandler(); + SimpleProperty prop = new SimpleProperty(EditModelScreen.this.model, this.animation); + if (prop.getLoopMode() == BlueprintAnimation.LoopMode.LOOP) { + prop.setSkipLastFrame(true); + } + + if (handler instanceof StateMachineHandler stateMachineHandler) { + if (stateMachineHandler.isPlayingAnimation(AnimationTab.this.priority.priority, this.animation.getName())) { + stateMachineHandler.stopAnimation(AnimationTab.this.priority.priority, this.animation.getName()); + } else { + stateMachineHandler.playAnimation(AnimationTab.this.priority.priority, prop, true); + } + } else if (handler.isPlayingAnimation(this.animation.getName())) { + handler.stopAnimation(this.animation.getName()); + } else { + handler.playAnimation(prop, true); + } + } + + public boolean update(boolean force) { + AnimationHandler handler = EditModelScreen.this.model.getAnimationHandler(); + IAnimationProperty property = handler instanceof StateMachineHandler stateMachineHandler + ? stateMachineHandler.getAnimation(AnimationTab.this.priority.priority, this.animation.getName()) + : handler.getAnimation(this.animation.getName()); + if (property == null) { + if (!force && this.trackedProperty == null) { + return false; + } + + this.trackedProperty = null; + this.stack = new ItemStack(Material.RED_CONCRETE); + ItemUtils.name(this.stack, Component.text(this.animation.getName(), ComponentUtil.color(NamedTextColor.RED))); + ItemUtils.lore( + this.stack, + Component.empty(), + Component.text("Animation:", ComponentUtil.reset()), + Component.text("- Animation ID: " + this.animation.getName(), ComponentUtil.reset()), + Component.text("- Loop Mode: " + this.animation.getLoopMode(), ComponentUtil.reset()), + Component.text("- Override: " + this.animation.isOverride(), ComponentUtil.reset()), + Component.text("- Length: " + MiscUtils.FORMATTER.format(this.animation.getLength()) + "s", ComponentUtil.reset()) + ); + } else { + if (!force && this.trackedProperty != null) { + int hash = this.trackedProperty.hashCode(); + if (hash == this.lastHash) { + return false; + } + + this.lastHash = hash; + } + + this.trackedProperty = property; + this.stack = new ItemStack(Material.LIME_CONCRETE); + ItemUtils.name(this.stack, Component.text(this.animation.getName(), ComponentUtil.color(NamedTextColor.GREEN))); + ItemUtils.lore( + this.stack, + Component.empty(), + Component.text("Animation:", ComponentUtil.reset()), + Component.text("- Animation ID: " + this.animation.getName(), ComponentUtil.reset()), + Component.text("- Loop Mode: " + this.animation.getLoopMode(), ComponentUtil.reset()), + Component.text("- Override: " + this.animation.isOverride(), ComponentUtil.reset()), + Component.text("- Length: " + MiscUtils.FORMATTER.format(this.animation.getLength()) + "s", ComponentUtil.reset()), + Component.empty(), + Component.text("Property:", ComponentUtil.reset()), + Component.text( + "- Phase: " + + property.getPhase() + + (property.getPhase() == IAnimationProperty.Phase.PLAY ? " (" + MiscUtils.FORMATTER.format(property.getTime()) + "s)" : ""), + ComponentUtil.reset() + ), + Component.text("- Forced Loop Mode: " + property.getForceLoopMode(), ComponentUtil.reset()), + Component.text("- Forced Override: " + property.getForceOverride(), ComponentUtil.reset()), + Component.text("- Speed: " + MiscUtils.FORMATTER.format(property.getSpeed()) + "x", ComponentUtil.reset()), + Component.text("- Lerp-In: " + MiscUtils.FORMATTER.format(property.getLerpIn()) + "s", ComponentUtil.reset()), + Component.text("- Lerp-Out: " + MiscUtils.FORMATTER.format(property.getLerpOut()) + "s", ComponentUtil.reset()) + ); + } + + return true; + } + } + + class PriorityButton implements Widget { + private static final int SLOT = 51; + private final ItemStack stack; + private int priority = 0; + + public PriorityButton() { + this.stack = new ItemStack(Material.COMPARATOR); + ItemUtils.name(this.stack, Component.text("Priority: " + this.priority, ComponentUtil.reset())); + ItemUtils.lore( + this.stack, + ((TextComponent)((TextComponent)((TextComponent)Component.empty().style(ComponentUtil.reset())).append(Component.text("<<< Left Click"))) + .append(Component.text(" | "))) + .append(Component.text("Right Click >>>")) + ); + } + + @Override + public ItemStack getItemForSlot(int size, int slot) { + return 51 == slot ? this.stack : null; + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + if (slot == 51) { + if (event.getClick().isLeftClick()) { + this.priority--; + } else if (event.getClick().isRightClick()) { + this.priority++; + } + + AnimationTab.this.page.refreshPage(screen); + ItemUtils.name(this.stack, Component.text("Priority: " + this.priority, ComponentUtil.reset())); + screen.markSlotsDirty(51); + } + } + } + } + + static class BoneButton implements PaginatorWidget.PageButton { + private final ModelBone bone; + private ItemStack stack; + + public BoneButton(ModelBone bone) { + this.bone = bone; + this.updateItem(); + } + + @Override + public ItemStack getItemStack() { + return this.stack; + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + this.bone.setVisible(!this.bone.isVisible()); + this.updateItem(); + screen.markSlotDirty(slot); + } + + private void updateItem() { + BlueprintBone blueprintBone = this.bone.getBlueprintBone(); + if (blueprintBone.isRenderer()) { + Collection items = blueprintBone.getModelData().createItemStack(); + if (!items.isEmpty()) { + this.stack = items.iterator().next(); + this.stack.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_DYE}); + } + } + + if (this.stack == null) { + this.stack = new ItemStack(Material.BONE); + } + + if (this.bone.isEnchanted()) { + this.stack.addUnsafeEnchantment(Enchantment.VANISHING_CURSE, 1); + this.stack.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ENCHANTS}); + } + + ItemUtils.name(this.stack, Component.text(this.bone.getUniqueBoneId(), ComponentUtil.reset())); + ArrayList lore = new ArrayList<>(); + lore.add(Component.empty()); + lore.add(Component.text("Bone ID: " + this.bone.getBoneId(), ComponentUtil.reset())); + if (this.bone.getParent() != null) { + lore.add(Component.text("Parent: " + this.bone.getParent().getBoneId(), ComponentUtil.reset())); + } + + lore.add(Component.text("Visible: " + this.bone.isVisible(), ComponentUtil.reset())); + int defColor = this.bone.getDefaultTint().asRGB(); + int dmgColor = this.bone.getDamageTint().asRGB(); + lore.add( + Component.text("Default Color: ", ComponentUtil.reset()) + .append(Component.text("#" + Integer.toString(defColor, 16).toUpperCase(Locale.ENGLISH), Style.style(TextColor.color(defColor)))) + ); + lore.add( + Component.text("Damage Color: ", ComponentUtil.reset()) + .append(Component.text("#" + Integer.toString(dmgColor, 16).toUpperCase(Locale.ENGLISH), Style.style(TextColor.color(dmgColor)))) + ); + lore.add(Component.text("Enchanted: " + this.bone.isEnchanted(), ComponentUtil.reset())); + boolean hasBehavior = false; + + for (Entry, BoneBehavior> behavior : this.bone.getImmutableBoneBehaviors().entrySet()) { + if (!behavior.getValue().isHidden()) { + if (!hasBehavior) { + hasBehavior = true; + lore.add(Component.text("Behavior: ", ComponentUtil.reset())); + } + + lore.add(Component.text("- " + behavior.getKey().getId(), ComponentUtil.reset())); + } + } + + ItemUtils.lore(this.stack, lore); + } + } + + class BoneTab implements TabWidget.Tab { + private final ItemStack stack = new ItemStack(Material.BONE); + private final PaginatorWidget page; + + public BoneTab() { + ItemUtils.name(this.stack, Component.text("Bones", ComponentUtil.reset())); + this.page = new PaginatorWidget(); + } + + @Override + public ItemStack getItemStack() { + return this.stack; + } + + @Override + public Widget getWidget() { + return this.page; + } + + @Override + public void onSelect() { + this.page.clearButtons(); + + for (ModelBone bone : EditModelScreen.this.model.getBones().values()) { + this.page.addButton(new EditModelScreen.BoneButton(bone)); + } + } + } + + class SettingsTab implements TabWidget.Tab { + private final ItemStack stack = new ItemStack(Material.COMMAND_BLOCK); + private final EditModelScreen.SettingsWidget widget; + + public SettingsTab() { + ItemUtils.name(this.stack, Component.text("Model Settings", ComponentUtil.reset())); + this.widget = EditModelScreen.this.new SettingsWidget(); + } + + @Override + public ItemStack getItemStack() { + return this.stack; + } + + @Override + public Widget getWidget() { + return this.widget; + } + + @Override + public void onSelect() { + } + } + + class SettingsWidget implements Widget { + private static final int RENDER_SCALE_SLOT = 21; + private static final int HITBOX_SCALE_SLOT = 22; + private static final int HITBOX_VISIBLE_SLOT = 23; + private static final int SHADOW_VISIBLE_SLOT = 30; + private static final int DEFAULT_TINT_SLOT = 31; + private static final int DAMAGE_TINT_SLOT = 32; + private static final int DAMAGE_TINT_VISIBLE_SLOT = 39; + private static final int PITCH_LOCK_SLOT = 40; + private static final int YAW_LOCK_SLOT = 41; + private final ItemStack renderScale = new ItemStack(Material.SLIME_BALL); + private final ItemStack hitboxScale = new ItemStack(Material.MAGMA_CREAM); + private final ItemStack hitboxVisible = new ItemStack(Material.SHULKER_SHELL); + private final ItemStack shadowVisible = new ItemStack(Material.BLACK_DYE); + private final ItemStack defaultTint = new ItemStack(Material.WHITE_DYE); + private final ItemStack damageTint = new ItemStack(Material.RED_DYE); + private final ItemStack damageTintVisible = new ItemStack(Material.DIAMOND_SWORD); + private final ItemStack pitchLock; + private final ItemStack yawLock; + + public SettingsWidget() { + ItemUtils.meta(this.damageTintVisible, meta -> meta.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ATTRIBUTES})); + this.pitchLock = new ItemStack(Material.CLOCK); + this.yawLock = new ItemStack(Material.COMPASS); + this.update(); + } + + @Override + public ItemStack getItemForSlot(int size, int slot) { + return switch (slot) { + case 21 -> this.renderScale; + case 22 -> this.hitboxScale; + case 23 -> this.hitboxVisible; + default -> null; + case 30 -> this.shadowVisible; + case 31 -> this.defaultTint; + case 32 -> this.damageTint; + case 39 -> this.damageTintVisible; + case 40 -> this.pitchLock; + case 41 -> this.yawLock; + }; + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + switch (slot) { + case 21: + player.closeInventory(); + ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter render scale:", ComponentUtil.color(NamedTextColor.AQUA))); + ChatListener.fetch( + player, + s -> { + try { + EditModelScreen.this.model.setScale(Double.parseDouble(s)); + ComponentUtil.sendMessage( + player, Component.text("[ModelEngine] Set render scale of model to " + s + ".", ComponentUtil.color(NamedTextColor.GREEN)) + ); + this.update(slot); + DualTicker.queueSyncTask(EditModelScreen.this::openScreen); + return true; + } catch (NumberFormatException var5) { + ComponentUtil.sendMessage( + player, Component.text("[ModelEngine] \"" + s + "\" is not a number. Try again.", ComponentUtil.color(NamedTextColor.RED)) + ); + return false; + } + } + ); + break; + case 22: + player.closeInventory(); + ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter hitbox scale:", ComponentUtil.color(NamedTextColor.AQUA))); + ChatListener.fetch( + player, + s -> { + try { + EditModelScreen.this.model.setHitboxScale(Double.parseDouble(s)); + ComponentUtil.sendMessage( + player, Component.text("[ModelEngine] Set hitbox scale of model to " + s + ".", ComponentUtil.color(NamedTextColor.GREEN)) + ); + this.update(slot); + DualTicker.queueSyncTask(EditModelScreen.this::openScreen); + return true; + } catch (NumberFormatException var5) { + ComponentUtil.sendMessage( + player, Component.text("[ModelEngine] \"" + s + "\" is not a number. Try again.", ComponentUtil.color(NamedTextColor.RED)) + ); + return false; + } + } + ); + break; + case 23: + EditModelScreen.this.model.setHitboxVisible(!EditModelScreen.this.model.isHitboxVisible()); + case 24: + case 25: + case 26: + case 27: + case 28: + case 29: + case 33: + case 34: + case 35: + case 36: + case 37: + case 38: + default: + break; + case 30: + EditModelScreen.this.model.setShadowVisible(!EditModelScreen.this.model.isShadowVisible()); + break; + case 31: + player.closeInventory(); + ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter default color in hex:", ComponentUtil.color(NamedTextColor.AQUA))); + ChatListener.fetch( + player, + s -> { + try { + if (s.startsWith("#")) { + s = s.substring(1); + } + + int color = Integer.parseInt(s, 16); + EditModelScreen.this.model.setDefaultTint(Color.fromRGB(color)); + ComponentUtil.sendMessage( + player, + ((TextComponent)Component.text("[ModelEngine] Set default color of model to ", ComponentUtil.color(NamedTextColor.GREEN)) + .append(Component.text("#" + s.toUpperCase(Locale.ENGLISH), ComponentUtil.color(TextColor.color(color))))) + .append(Component.text(".")) + ); + this.update(slot); + DualTicker.queueSyncTask(EditModelScreen.this::openScreen); + return true; + } catch (NumberFormatException var5) { + ComponentUtil.sendMessage( + player, Component.text("[ModelEngine] \"" + s + "\" is not a valid color. Try again.", ComponentUtil.color(NamedTextColor.RED)) + ); + return false; + } + } + ); + break; + case 32: + player.closeInventory(); + ComponentUtil.sendMessage(player, Component.text("[ModelEngine] Enter damage color in hex:", ComponentUtil.color(NamedTextColor.AQUA))); + ChatListener.fetch( + player, + s -> { + try { + if (s.startsWith("#")) { + s = s.substring(1); + } + + int color = Integer.parseInt(s, 16); + EditModelScreen.this.model.setDamageTint(Color.fromRGB(color)); + ComponentUtil.sendMessage( + player, + ((TextComponent)Component.text("[ModelEngine] Set damage color of model to ", ComponentUtil.color(NamedTextColor.GREEN)) + .append(Component.text("#" + s.toUpperCase(Locale.ENGLISH), ComponentUtil.color(TextColor.color(color))))) + .append(Component.text(".")) + ); + this.update(slot); + DualTicker.queueSyncTask(EditModelScreen.this::openScreen); + return true; + } catch (NumberFormatException var5) { + ComponentUtil.sendMessage( + player, Component.text("[ModelEngine] \"" + s + "\" is not a valid color. Try again.", ComponentUtil.color(NamedTextColor.RED)) + ); + return false; + } + } + ); + break; + case 39: + EditModelScreen.this.model.setCanHurt(!EditModelScreen.this.model.canHurt()); + break; + case 40: + EditModelScreen.this.model.setLockPitch(!EditModelScreen.this.model.isLockPitch()); + break; + case 41: + EditModelScreen.this.model.setLockYaw(!EditModelScreen.this.model.isLockYaw()); + } + + this.update(slot); + EditModelScreen.this.markSlotDirty(slot); + } + + public void update() { + this.update(21); + this.update(22); + this.update(23); + this.update(30); + this.update(31); + this.update(32); + this.update(39); + this.update(40); + this.update(41); + } + + public void update(int slot) { + switch (slot) { + case 21: + ItemUtils.name( + this.renderScale, + Component.text("Render Scale: " + MiscUtils.FORMATTER.format(EditModelScreen.this.model.getScale().x()), ComponentUtil.reset()) + ); + break; + case 22: + ItemUtils.name( + this.hitboxScale, + Component.text("Hitbox Scale: " + MiscUtils.FORMATTER.format(EditModelScreen.this.model.getHitboxScale().x()), ComponentUtil.reset()) + ); + break; + case 23: + ItemUtils.name( + this.hitboxVisible, + Component.text( + "Hitbox Visible: " + EditModelScreen.this.model.isHitboxVisible(), + ComponentUtil.color(EditModelScreen.this.model.isHitboxVisible() ? NamedTextColor.GREEN : NamedTextColor.RED) + ) + ); + case 24: + case 25: + case 26: + case 27: + case 28: + case 29: + case 33: + case 34: + case 35: + case 36: + case 37: + case 38: + default: + break; + case 30: + ItemUtils.name( + this.shadowVisible, + Component.text( + "Shadow Visible: " + EditModelScreen.this.model.isShadowVisible(), + ComponentUtil.color(EditModelScreen.this.model.isShadowVisible() ? NamedTextColor.GREEN : NamedTextColor.RED) + ) + ); + break; + case 31: + ItemUtils.name( + this.defaultTint, + Component.text( + "Default Tint: #" + Integer.toHexString(EditModelScreen.this.model.getDefaultTint().asARGB()).toUpperCase(Locale.ENGLISH).substring(2), + ComponentUtil.color(TextColor.color(EditModelScreen.this.model.getDefaultTint().asRGB())) + ) + ); + break; + case 32: + ItemUtils.name( + this.damageTint, + Component.text( + "Damage Tint: #" + Integer.toHexString(EditModelScreen.this.model.getDamageTint().asARGB()).toUpperCase(Locale.ENGLISH).substring(2), + ComponentUtil.color(TextColor.color(EditModelScreen.this.model.getDamageTint().asRGB())) + ) + ); + break; + case 39: + ItemUtils.name( + this.damageTintVisible, + Component.text( + "Damage Tint Visible: " + EditModelScreen.this.model.canHurt(), + ComponentUtil.color(EditModelScreen.this.model.canHurt() ? NamedTextColor.GREEN : NamedTextColor.RED) + ) + ); + break; + case 40: + ItemUtils.name( + this.pitchLock, + Component.text( + "Pitch Lock: " + EditModelScreen.this.model.isLockPitch(), + ComponentUtil.color(EditModelScreen.this.model.isLockPitch() ? NamedTextColor.GREEN : NamedTextColor.RED) + ) + ); + break; + case 41: + ItemUtils.name( + this.yawLock, + Component.text( + "Yaw Lock: " + EditModelScreen.this.model.isLockYaw(), + ComponentUtil.color(EditModelScreen.this.model.isLockYaw() ? NamedTextColor.GREEN : NamedTextColor.RED) + ) + ); + } + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/screen/NavigationScreen.java b/core/src/main/java/com/ticxo/modelengine/core/menu/screen/NavigationScreen.java new file mode 100644 index 0000000..947b8bc --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/screen/NavigationScreen.java @@ -0,0 +1,139 @@ +package com.ticxo.modelengine.core.menu.screen; + +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.menu.Widget; +import com.ticxo.modelengine.api.utils.data.ComponentUtil; +import com.ticxo.modelengine.api.utils.data.ItemUtils; +import com.ticxo.modelengine.core.menu.SelectionManager; +import com.ticxo.modelengine.core.menu.widget.BorderWidget; +import com.ticxo.modelengine.core.menu.widget.CloseWidget; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; + +public class NavigationScreen extends AbstractScreen { + public NavigationScreen(Player player) { + super(player, "Model Engine", 6); + this.addWidget(new BorderWidget()); + this.addWidget(new NavigationScreen.Navigator()); + this.addWidget(new CloseWidget(null)); + } + + class Navigator implements Widget { + private static final int SPAWN_SLOT = 29; + private static final int SELECT_SLOT = 31; + private static final int EDIT_SLOT = 33; + private final ItemStack spawn; + private final ItemStack select; + private final ItemStack edit; + private Entity selected; + + public Navigator() { + if (SelectionManager.isSelecting(NavigationScreen.this.viewer)) { + SelectionManager.setSelecting(NavigationScreen.this.viewer, false); + NavigationScreen.this.viewer + .sendActionBar(((TextComponent)Component.empty().style(ComponentUtil.reset())).append(Component.text("Canceled selection mode."))); + } + + this.spawn = new ItemStack(Material.PIG_SPAWN_EGG); + ItemUtils.name(this.spawn, Component.text("Spawn Model", ComponentUtil.reset())); + ItemUtils.lore(this.spawn, Component.empty(), Component.text("Spawn a model at where you are standing.", ComponentUtil.reset())); + this.selected = SelectionManager.getSelected(NavigationScreen.this.viewer); + this.select = new ItemStack(Material.SPYGLASS); + this.updateSelect(); + this.edit = new ItemStack(Material.WRITABLE_BOOK); + ItemUtils.name(this.edit, Component.text("Edit Entity", ComponentUtil.reset())); + ItemUtils.lore( + this.edit, + Component.empty(), + Component.text("Add or remove models, states, and edit", ComponentUtil.reset()), + Component.text("bone behaviors of the selected entity.", ComponentUtil.reset()) + ); + } + + @Override + public ItemStack getItemForSlot(int size, int slot) { + return switch (slot) { + case 29 -> this.spawn; + default -> null; + case 31 -> this.select; + case 33 -> this.edit; + }; + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + ClickType click = event.getClick(); + if (!click.isKeyboardClick()) { + switch (slot) { + case 29: + new SpawnModelScreen(NavigationScreen.this, player).openScreen(); + case 30: + case 32: + default: + break; + case 31: + switch (click) { + case RIGHT: + SelectionManager.setSelected(player, player); + player.sendActionBar(Component.text("Select " + player.getName() + ".", ComponentUtil.reset())); + this.selected = player; + this.updateSelect(); + NavigationScreen.this.markSlotDirty(31); + return; + case LEFT: + SelectionManager.setSelecting(player, true); + player.sendActionBar(Component.text("Select an entity by attacking the target.", ComponentUtil.reset())); + player.closeInventory(); + return; + case SHIFT_LEFT: + case SHIFT_RIGHT: + SelectionManager.setSelected(player, null); + this.selected = null; + this.updateSelect(); + NavigationScreen.this.markSlotDirty(31); + return; + default: + return; + } + case 33: + Entity entity = SelectionManager.getSelected(player); + if (entity != null) { + new EditEntityScreen(NavigationScreen.this, player, entity).openScreen(); + } + } + } + } + + private void updateSelect() { + ItemUtils.name(this.select, Component.text("Select Entity", ComponentUtil.reset())); + ItemUtils.lore( + this.select, + Component.empty(), + this.selected == null + ? null + : ((TextComponent)Component.empty().style(ComponentUtil.reset().decoration(TextDecoration.BOLD, true).color(NamedTextColor.AQUA))) + .append(Component.text("Selected: " + this.selected.getName())), + this.selected == null ? null : Component.empty(), + Component.text("Left click to select entity.", ComponentUtil.reset()), + Component.text("Right click to select yourself.", ComponentUtil.reset()), + Component.text("Shift click to clear selection.", ComponentUtil.reset()) + ); + this.select.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_ENCHANTS}); + if (this.selected != null) { + this.select.addUnsafeEnchantment(Enchantment.VANISHING_CURSE, 1); + } else { + this.select.removeEnchantment(Enchantment.VANISHING_CURSE); + } + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/screen/SpawnModelScreen.java b/core/src/main/java/com/ticxo/modelengine/core/menu/screen/SpawnModelScreen.java new file mode 100644 index 0000000..aa47923 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/screen/SpawnModelScreen.java @@ -0,0 +1,76 @@ +package com.ticxo.modelengine.core.menu.screen; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelRegistry; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.type.PlayerLimb; +import com.ticxo.modelengine.api.model.bone.type.UserLimb; +import com.ticxo.modelengine.api.utils.data.ComponentUtil; +import com.ticxo.modelengine.api.utils.data.ItemUtils; +import com.ticxo.modelengine.core.menu.widget.BasicItemWidget; +import com.ticxo.modelengine.core.menu.widget.BorderWidget; +import com.ticxo.modelengine.core.menu.widget.CloseWidget; +import com.ticxo.modelengine.core.menu.widget.PaginatorWidget; +import com.ticxo.modelengine.core.menu.widget.page.AbstractModelButton; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Pig; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class SpawnModelScreen extends AbstractScreen { + public SpawnModelScreen(AbstractScreen rootScreen, Player viewer) { + super(viewer, "Spawn Model", 6); + this.addWidget(new BorderWidget()); + PaginatorWidget page = new PaginatorWidget(); + ModelRegistry registry = ModelEngineAPI.getAPI().getModelRegistry(); + + for (String modelId : registry.getOrderedId()) { + ModelBlueprint blueprint = registry.get(modelId); + SpawnModelScreen.ModelButton button = new SpawnModelScreen.ModelButton(blueprint); + page.addButton(button); + } + + this.addWidget(page); + ItemStack statSign = new ItemStack(Material.OAK_SIGN); + ItemUtils.name(statSign, Component.text("Stats", ComponentUtil.reset().decoration(TextDecoration.BOLD, true))); + ItemUtils.lore(statSign, Component.empty(), Component.text("Models: " + registry.getKeys().size(), ComponentUtil.reset())); + this.addWidget(new BasicItemWidget(53, statSign)); + this.addWidget(new CloseWidget(rootScreen)); + } + + static class ModelButton extends AbstractModelButton { + public ModelButton(ModelBlueprint blueprint) { + super(blueprint); + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + if (event.isLeftClick() || event.isRightClick()) { + Location location = player.getLocation(); + player.getWorld().spawn(location, Pig.class, entity -> { + BukkitEntity base = new BukkitEntity(entity); + base.getBodyRotationController().setYBodyRot(location.getYaw()); + ModeledEntity modeledEntity = ModelEngineAPI.createModeledEntity(base); + modeledEntity.setBaseEntityVisible(false); + ActiveModel activeModel = ModelEngineAPI.createActiveModel(this.blueprint); + activeModel.setAutoRendererInitialization(false); + modeledEntity.addModel(activeModel, true).ifPresent(ActiveModel::destroy); + activeModel.getBones().values().forEach(modelBone -> { + modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(playerLimb -> ((PlayerLimb)playerLimb).setTexture(player)); + modelBone.getBoneBehavior(BoneBehaviorTypes.USER_LIMB).ifPresent(playerLimb -> ((UserLimb)playerLimb).setTexture(player)); + }); + activeModel.initializeRenderer(); + }); + } + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/widget/BasicItemWidget.java b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/BasicItemWidget.java new file mode 100644 index 0000000..edea61e --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/BasicItemWidget.java @@ -0,0 +1,26 @@ +package com.ticxo.modelengine.core.menu.widget; + +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.menu.Widget; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class BasicItemWidget implements Widget { + private final int slot; + private final ItemStack stack; + + @Override + public ItemStack getItemForSlot(int size, int slot) { + return this.slot == slot ? this.stack : null; + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + } + + public BasicItemWidget(int slot, ItemStack stack) { + this.slot = slot; + this.stack = stack; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/widget/BorderWidget.java b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/BorderWidget.java new file mode 100644 index 0000000..e753454 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/BorderWidget.java @@ -0,0 +1,34 @@ +package com.ticxo.modelengine.core.menu.widget; + +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.menu.Widget; +import com.ticxo.modelengine.api.utils.data.ItemUtils; +import net.kyori.adventure.text.Component; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class BorderWidget implements Widget { + private final ItemStack border = new ItemStack(Material.TWISTING_VINES); + private final ItemStack bar; + + public BorderWidget() { + ItemUtils.name(this.border, Component.text(" ")); + this.bar = new ItemStack(Material.NETHER_SPROUTS); + ItemUtils.name(this.bar, Component.text(" ")); + } + + @Override + public ItemStack getItemForSlot(int size, int slot) { + if (slot % 9 == 0 || slot % 9 == 8) { + return this.border; + } else { + return (slot < 9 || slot >= 18) && slot <= size - 9 ? null : this.bar; + } + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/widget/CloseWidget.java b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/CloseWidget.java new file mode 100644 index 0000000..0280c0d --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/CloseWidget.java @@ -0,0 +1,38 @@ +package com.ticxo.modelengine.core.menu.widget; + +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.menu.Widget; +import com.ticxo.modelengine.api.utils.data.ComponentUtil; +import com.ticxo.modelengine.api.utils.data.ItemUtils; +import net.kyori.adventure.text.Component; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +public class CloseWidget implements Widget { + private final ItemStack close = new ItemStack(Material.BARRIER); + private final AbstractScreen rootScreen; + + public CloseWidget(@Nullable AbstractScreen screen) { + ItemUtils.name(this.close, Component.text("Close", ComponentUtil.reset())); + this.rootScreen = screen; + } + + @Override + public ItemStack getItemForSlot(int size, int slot) { + return slot == size - 5 ? this.close : null; + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + if (slot == screen.getInventory().getSize() - 5) { + if (this.rootScreen == null) { + player.closeInventory(); + } else { + this.rootScreen.openScreen(); + } + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/widget/CompositeWidget.java b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/CompositeWidget.java new file mode 100644 index 0000000..d7f21d1 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/CompositeWidget.java @@ -0,0 +1,29 @@ +package com.ticxo.modelengine.core.menu.widget; + +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.menu.Widget; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class CompositeWidget implements Widget { + private final Widget first; + private final Widget second; + + @Override + public ItemStack getItemForSlot(int size, int slot) { + ItemStack sItem = this.second.getItemForSlot(size, slot); + return sItem != null ? sItem : this.first.getItemForSlot(size, slot); + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + this.second.onClick(screen, player, slot, event); + this.first.onClick(screen, player, slot, event); + } + + public CompositeWidget(Widget first, Widget second) { + this.first = first; + this.second = second; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/widget/PaginatorWidget.java b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/PaginatorWidget.java new file mode 100644 index 0000000..8813557 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/PaginatorWidget.java @@ -0,0 +1,119 @@ +package com.ticxo.modelengine.core.menu.widget; + +import com.google.common.collect.ImmutableMap; +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.menu.Widget; +import com.ticxo.modelengine.api.utils.data.ComponentUtil; +import com.ticxo.modelengine.api.utils.data.ItemUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class PaginatorWidget implements Widget { + private static final int PAGE_SLOT = 52; + private static final int MAX_ITEM = 21; + private static final Map PAGE_PAIR; + private final ItemStack pageSwitch; + private final List buttons = new ArrayList<>(); + private int currentPage; + + public PaginatorWidget() { + this.pageSwitch = new ItemStack(Material.PAPER); + ItemUtils.name(this.pageSwitch, Component.text("Turn Page", ComponentUtil.reset())); + } + + @Override + public ItemStack getItemForSlot(int size, int slot) { + if (slot == 52) { + ItemUtils.lore( + this.pageSwitch, + ((TextComponent)((TextComponent)((TextComponent)Component.empty().style(ComponentUtil.reset())) + .append(Component.text("<<< Left Click").color(this.currentPage == 0 ? NamedTextColor.DARK_GRAY : NamedTextColor.WHITE))) + .append(Component.text(" | "))) + .append(Component.text("Right Click >>>").color(this.currentPage == this.getLastPage() ? NamedTextColor.DARK_GRAY : NamedTextColor.WHITE)) + ); + return this.pageSwitch; + } else { + PaginatorWidget.PageButton button = this.getButton(slot); + return button == null ? null : button.getItemStack(); + } + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + if (slot == 52) { + if (event.getClick().isLeftClick()) { + this.currentPage--; + } else if (event.getClick().isRightClick()) { + this.currentPage++; + } + + this.currentPage = TMath.clamp(this.currentPage, 0, this.getLastPage()); + screen.markSlotsDirty(52); + this.refreshPage(screen); + } else { + PaginatorWidget.PageButton button = this.getButton(slot); + if (button != null) { + button.onClick(screen, player, slot, event); + } + } + } + + public void addButton(PaginatorWidget.PageButton button) { + this.buttons.add(button); + } + + public void clearButtons() { + this.buttons.clear(); + } + + public PaginatorWidget.PageButton getButton(int slot) { + Integer id = PAGE_PAIR.get(slot); + if (id == null) { + return null; + } else { + id = this.currentPage * 21 + id; + return id < this.buttons.size() ? this.buttons.get(id) : null; + } + } + + public void refreshPage(AbstractScreen screen) { + PAGE_PAIR.forEach((invSlot, id) -> screen.markSlotDirty(invSlot)); + } + + private int getLastPage() { + return Math.max(TMath.ceil(this.buttons.size() / 21.0F) - 1, 0); + } + + static { + HashMap pair = new HashMap<>(); + int id = 0; + + for (int i = 19; i <= 43; i++) { + switch (i % 9) { + default: + pair.put(i, id++); + break; + case 0: + case 8: + } + } + + PAGE_PAIR = ImmutableMap.copyOf(pair); + } + + public interface PageButton { + ItemStack getItemStack(); + + void onClick(AbstractScreen var1, Player var2, int var3, InventoryClickEvent var4); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/widget/TabWidget.java b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/TabWidget.java new file mode 100644 index 0000000..deac601 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/TabWidget.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.core.menu.widget; + +import com.ticxo.modelengine.api.menu.AbstractScreen; +import com.ticxo.modelengine.api.menu.Widget; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +public class TabWidget implements Widget { + private final List tabs = new ArrayList<>(); + private TabWidget.Tab selectedTab; + + @Override + public ItemStack getItemForSlot(int size, int slot) { + if (slot != 0 && slot < 8) { + return this.tabs.size() < slot ? null : this.tabs.get(slot - 1).getItemStack(); + } else { + return this.selectedTab == null ? null : this.selectedTab.getWidget().getItemForSlot(size, slot); + } + } + + @Override + public void onClick(AbstractScreen screen, Player player, int slot, InventoryClickEvent event) { + if (slot != 0 && slot < 8) { + if (this.tabs.size() >= slot) { + TabWidget.Tab t = this.tabs.get(slot - 1); + if (this.selectedTab != t) { + this.selectedTab = t; + this.selectedTab.onSelect(); + screen.draw(true); + } + } + } else { + if (this.selectedTab != null) { + this.selectedTab.getWidget().onClick(screen, player, slot, event); + } + } + } + + public void addTab(TabWidget.Tab tab) { + this.tabs.add(tab); + if (this.selectedTab == null) { + this.selectedTab = tab; + this.selectedTab.onSelect(); + } + } + + public void clearTab() { + this.tabs.clear(); + } + + public TabWidget.Tab getSelectedTab() { + return this.selectedTab; + } + + public interface Tab { + ItemStack getItemStack(); + + Widget getWidget(); + + void onSelect(); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/menu/widget/page/AbstractModelButton.java b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/page/AbstractModelButton.java new file mode 100644 index 0000000..9b7ed63 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/menu/widget/page/AbstractModelButton.java @@ -0,0 +1,55 @@ +package com.ticxo.modelengine.core.menu.widget.page; + +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.utils.data.ComponentUtil; +import com.ticxo.modelengine.api.utils.data.ItemUtils; +import com.ticxo.modelengine.core.menu.widget.PaginatorWidget; +import java.util.Collection; +import net.kyori.adventure.text.Component; +import org.bukkit.Material; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; + +public abstract class AbstractModelButton implements PaginatorWidget.PageButton { + protected final ModelBlueprint blueprint; + protected final ItemStack stack; + + public AbstractModelButton(ModelBlueprint blueprint) { + this.blueprint = blueprint; + ItemStack bone = null; + BlueprintBone headBone = blueprint.getFlatMap().get("head"); + if (headBone != null && headBone.isRenderer()) { + Collection items = headBone.getModelData().createItemStack(); + if (!items.isEmpty()) { + bone = items.iterator().next(); + bone.addItemFlags(new ItemFlag[]{ItemFlag.HIDE_DYE}); + } + } + + if (bone == null) { + bone = new ItemStack(Material.ARMOR_STAND); + } + + this.stack = bone; + this.updateItem(); + } + + protected void updateItem() { + ItemUtils.name(this.stack, Component.text(this.blueprint.getName(), ComponentUtil.reset())); + ItemUtils.lore( + this.stack, + Component.empty(), + Component.text("Model ID: " + this.blueprint.getName(), ComponentUtil.reset()), + Component.text("Hitbox: " + this.blueprint.getMainHitbox().toSimpleString(), ComponentUtil.reset()), + Component.text("Eye Height: " + this.blueprint.getMainHitbox().toEyeHeightString(), ComponentUtil.reset()), + Component.text("Shadow: " + this.blueprint.getShadowRadius(), ComponentUtil.reset()), + Component.text("Bone Count: " + this.blueprint.getFlatMap().size(), ComponentUtil.reset()) + ); + } + + @Override + public ItemStack getItemStack() { + return this.stack; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/misc/Alternator.java b/core/src/main/java/com/ticxo/modelengine/core/misc/Alternator.java new file mode 100644 index 0000000..078f4cf --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/misc/Alternator.java @@ -0,0 +1,133 @@ +package com.ticxo.modelengine.core.misc; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.ItemDisplay; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Transformation; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class Alternator { + private static final Quaternionf IDENTITY = new Quaternionf(); + private final int tick; + private final ItemDisplay displayA; + private final ItemDisplay displayB; + private boolean isAVisible; + private boolean queueNextTickToggle; + private Vector3f position = new Vector3f(); + private boolean positionStep; + private Quaternionf rotation = new Quaternionf(); + private boolean rotationStep; + private Vector3f scale = new Vector3f(1.0F, 1.0F, 1.0F); + private boolean scaleStep; + + public Alternator(Location location, int tick) { + this.tick = tick; + this.displayA = (ItemDisplay)location.getWorld().spawn(location, ItemDisplay.class, itemDisplay -> { + itemDisplay.setInterpolationDuration(tick); + itemDisplay.setItemStack(new ItemStack(Material.CARVED_PUMPKIN)); + }); + this.displayB = (ItemDisplay)location.getWorld().spawn(location, ItemDisplay.class, itemDisplay -> { + itemDisplay.setInterpolationDuration(tick); + itemDisplay.setItemStack(new ItemStack(Material.FURNACE)); + itemDisplay.setViewRange(0.0F); + }); + this.isAVisible = true; + } + + public void tick() { + this.tickSwap(); + ItemDisplay visible = this.getVisible(); + ItemDisplay hidden = this.getHidden(); + if (!this.positionStep && !this.rotationStep && !this.scaleStep) { + Transformation transformation = new Transformation(this.position, this.rotation, this.scale, IDENTITY); + visible.setTransformation(transformation); + visible.setInterpolationDelay(0); + visible.setInterpolationDuration(this.tick); + } else { + Vector3f dPos = this.positionStep ? visible.getTransformation().getTranslation() : this.position; + Quaternionf dRot = this.rotationStep ? visible.getTransformation().getLeftRotation() : this.rotation; + Vector3f dSca = this.scaleStep ? visible.getTransformation().getScale() : this.scale; + Transformation visibleTransform = new Transformation(dPos, dRot, dSca, IDENTITY); + Transformation hiddenTransform = new Transformation(this.position, this.rotation, this.scale, IDENTITY); + if (!visible.getTransformation().equals(visibleTransform)) { + visible.setTransformation(visibleTransform); + visible.setInterpolationDelay(0); + visible.setInterpolationDuration(this.tick); + } + + if (!hidden.getTransformation().equals(hiddenTransform)) { + hidden.setTransformation(hiddenTransform); + hidden.setInterpolationDelay(0); + hidden.setInterpolationDuration(0); + } + + this.queueNextTickToggle = true; + this.positionStep = false; + this.rotationStep = false; + this.scaleStep = false; + } + } + + public void tickSwap() { + if (this.queueNextTickToggle) { + this.swapVisibility(); + this.queueNextTickToggle = false; + } + } + + public ItemDisplay getVisible() { + return this.isAVisible ? this.displayA : this.displayB; + } + + public ItemDisplay getHidden() { + return !this.isAVisible ? this.displayA : this.displayB; + } + + public void swapVisibility() { + this.getVisible().setViewRange(0.0F); + this.getHidden().setViewRange(1.0F); + this.isAVisible = !this.isAVisible; + } + + public boolean isDead() { + return this.displayA.isDead() || this.displayB.isDead(); + } + + public Alternator lerpPosition(Vector3f position) { + this.position = position; + this.positionStep = false; + return this; + } + + public Alternator lerpRotation(Quaternionf rotation) { + this.rotation = rotation; + this.rotationStep = false; + return this; + } + + public Alternator lerpScale(Vector3f scale) { + this.scale = scale; + this.scaleStep = false; + return this; + } + + public Alternator stepPosition(Vector3f position) { + this.position = position; + this.positionStep = true; + return this; + } + + public Alternator stepRotation(Quaternionf rotation) { + this.rotation = rotation; + this.rotationStep = true; + return this; + } + + public Alternator stepScale(Vector3f scale) { + this.scale = scale; + this.scaleStep = true; + return this; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/misc/Cardinal.java b/core/src/main/java/com/ticxo/modelengine/core/misc/Cardinal.java new file mode 100644 index 0000000..ed2ba31 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/misc/Cardinal.java @@ -0,0 +1,54 @@ +package com.ticxo.modelengine.core.misc; + +import org.apache.commons.lang3.tuple.Triple; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public enum Cardinal { + Q_001(0, 0, 1), + Q_002(0, 0, 2), + Q_003(0, 0, 3), + Q_010(0, 1, 0), + Q_011(0, 1, 1), + Q_012(0, 1, 2), + Q_013(0, 1, 3), + Q_020(0, 2, 0), + Q_021(0, 2, 1), + Q_022(0, 2, 2), + Q_023(0, 2, 3), + Q_030(0, 3, 0), + Q_031(0, 3, 1), + Q_032(0, 3, 2), + Q_033(0, 3, 3), + Q_100(1, 0, 0), + Q_101(1, 0, 1), + Q_102(1, 0, 2), + Q_103(1, 0, 3), + Q_120(1, 2, 0), + Q_121(1, 2, 1), + Q_122(1, 2, 2), + Q_123(1, 2, 3); + + public final Quaternionf rotation; + public final Quaternionf inverse; + private static final Cardinal[] VALUES = values(); + + private Cardinal(int x, int y, int z) { + this.rotation = new Quaternionf().rotationXYZ(x * (float) (Math.PI / 2), y * (float) (Math.PI / 2), z * (float) (Math.PI / 2)); + this.inverse = this.rotation.invert(new Quaternionf()); + } + + public static Cardinal[] cardinals() { + return VALUES; + } + + public Triple warpTransform(Quaternionf left, Vector3f scale, Quaternionf right) { + Quaternionf nLeft = left.mul(this.rotation, new Quaternionf()); + Vector3f nScale = scale.rotate(this.inverse, new Vector3f()); + nScale.x = Math.signum(scale.x) * Math.abs(nScale.x); + nScale.y = Math.signum(scale.y) * Math.abs(nScale.y); + nScale.z = Math.signum(scale.z) * Math.abs(nScale.z); + Quaternionf nRight = right.premul(this.inverse, new Quaternionf()); + return Triple.of(nLeft, nScale, nRight); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/ActiveModelImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/ActiveModelImpl.java new file mode 100644 index 0000000..35dc6c9 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/ActiveModelImpl.java @@ -0,0 +1,896 @@ +package com.ticxo.modelengine.core.model; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.handler.AnimationHandler; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.utils.callback.Callback; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.CachedImmutableMap; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.meta.MetadataRegistry; +import com.ticxo.modelengine.core.animation.handler.PriorityHandler; +import com.ticxo.modelengine.core.animation.handler.StateMachineHandler; +import com.ticxo.modelengine.core.model.bone.ModelBoneImpl; +import com.ticxo.modelengine.core.model.render.DisplayRendererImpl; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.function.Consumer; +import java.util.function.Function; +import org.bukkit.Color; +import org.bukkit.entity.Display.Billboard; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class ActiveModelImpl implements ActiveModel { + private final ModelBlueprint blueprint; + private final MetadataRegistry metadata = new MetadataRegistry(); + private final ModelRenderer modelRenderer; + private final AnimationHandler animationHandler; + private final Map bones = Maps.newConcurrentMap(); + private final Map roots = Maps.newConcurrentMap(); + private final Map, BehaviorManager> behaviorManagers = new LinkedHashMap<>(); + private final Map, BehaviorRenderer> behaviorRenderers = new LinkedHashMap<>(); + private final CachedImmutableMap boneCache = new CachedImmutableMap<>(this.bones); + private final CachedImmutableMap, BehaviorManager> behaviorManagerCache = new CachedImmutableMap<>(this.behaviorManagers); + private final CachedImmutableMap, BehaviorRenderer> behaviorRendererCache = new CachedImmutableMap<>(this.behaviorRenderers); + private final Vector3f scale = new Vector3f(1.0F, 1.0F, 1.0F); + private final Vector3f hitboxScale = new Vector3f(1.0F, 1.0F, 1.0F); + private UUID pivotOverride; + private ModeledEntity modeledEntity; + private boolean mainHitbox; + private boolean generated; + private boolean destroyed; + private boolean removed; + private boolean autoRendererInitialization = true; + private boolean hitboxVisible = true; + private boolean shadowVisible = true; + private float viewRange = 4096.0F; + private boolean canHurt = true; + private Color defaultTint = Color.fromRGB(16777215); + private Color damageTint = Color.fromRGB(16737894); + private boolean wasMarkedHurt; + private Boolean glowing; + private Integer glowColor; + private Set glowAudience; + private int blockLight = -1; + private int skyLight = -1; + private Billboard billboard = Billboard.FIXED; + private Boolean onFire; + private Boolean renderFire; + private boolean lockPitch; + private boolean lockYaw; + private float lockedYHeadRot = 0.0F; + private float lockedXHeadRot = 0.0F; + private float lockedYBodyRot = 0.0F; + private Boolean modelRotationLocked; + private boolean invisUpdate; + private boolean cameraPivot; + private final BoneSequencer boneSequencer = new BoneSequencer(); + private ActiveModelImpl.ResolvedBoneOrder resolvedBoneOrder; + private final Callback scaleCallback = new Callback<>( + scales -> (model, scale) -> scales.forEach(callback -> callback.onScale(model, scale)) + ); + private final Callback preSendCallback = new Callback<>(preSends -> () -> preSends.forEach(Runnable::run)); + private final Callback postSendCallback = new Callback<>(postSends -> () -> postSends.forEach(Runnable::run)); + + public ActiveModelImpl( + @NotNull ModelBlueprint blueprint, + @Nullable Function rendererSupplier, + @Nullable Function handlerSupplier + ) { + this.blueprint = blueprint; + ModelRenderer renderer = (ModelRenderer)(rendererSupplier == null ? new DisplayRendererImpl(this) : rendererSupplier.apply(this)); + this.modelRenderer = (ModelRenderer)(renderer == null ? new DisplayRendererImpl(this) : renderer); + AnimationHandler handler = handlerSupplier == null ? createDefaultHandler(this) : handlerSupplier.apply(this); + this.animationHandler = handler == null ? createDefaultHandler(this) : handler; + } + + private static AnimationHandler createDefaultHandler(ActiveModel activeModel) { + return (AnimationHandler)(ConfigProperty.USE_STATE_MACHINE.getBoolean() ? new StateMachineHandler(activeModel) : new PriorityHandler(activeModel)); + } + + public static ActiveModel fromData(SavedData data) { + try { + return ModelEngineAPI.createActiveModel( + data.getString("blueprint"), + null, + activeModel -> { + activeModel.setMainHitbox(data.getBoolean("main_hitbox")); + return data.getData("animation_handler") + .map(handlerData -> ModelEngineAPI.getAnimationHandlerRegistry().createHandler(activeModel, handlerData)) + .orElse(null); + } + ); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + @Override + public Optional getPivotOverride() { + return ModelEngineAPI.getPivotOverrideRegistry().get(this.pivotOverride); + } + + @Override + public void setPivotOverride(PivotOverride override) { + this.modelRenderer.updatePivotOverride(override); + this.pivotOverride = override.getUuid(); + } + + @Override + public Map getBones() { + return this.boneCache.get(); + } + + @Override + public Map, BehaviorManager> getBehaviorManagers() { + Map, BehaviorManager> cached = this.behaviorManagerCache.getIfCached(); + if (cached != null) { + return cached; + } else { + synchronized (this.behaviorManagers) { + return this.behaviorManagerCache.get(); + } + } + } + + @Override + public Map, BehaviorRenderer> getBehaviorRenderers() { + Map, BehaviorRenderer> cached = this.behaviorRendererCache.getIfCached(); + if (cached != null) { + return cached; + } else { + synchronized (this.behaviorRenderers) { + return this.behaviorRendererCache.get(); + } + } + } + + @Override + public Vector3fc getScale() { + return this.scale; + } + + @Override + public void setScale(double scale) { + this.setScale(new Vector3f((float)scale, (float)scale, (float)scale)); + } + + @Override + public void setScale(Vector3fc scale) { + this.scale.set(scale); + this.scaleCallback.invoker().onScale(this, scale.get(scale.maxComponent())); + if (this.mainHitbox && this.modeledEntity != null) { + Vector3fc scaleVec = this.getScale(); + Hitbox mainHitbox = this.blueprint.getMainHitbox(); + Hitbox scaledRenderHitbox = new Hitbox( + mainHitbox.getWidth() * scaleVec.x(), + mainHitbox.getHeight() * scaleVec.y(), + mainHitbox.getDepth() * scaleVec.z(), + mainHitbox.getEyeHeight() * scaleVec.y() + ); + this.modeledEntity.getBase().getData().setCullHitbox(scaledRenderHitbox); + } + } + + @Override + public Vector3fc getHitboxScale() { + return this.hitboxScale; + } + + @Override + public void setHitboxScale(double scale) { + this.setHitboxScale(new Vector3f((float)scale, (float)scale, (float)scale)); + } + + @Override + public void setHitboxScale(Vector3fc scale) { + this.hitboxScale.set(scale); + if (this.mainHitbox && this.modeledEntity != null) { + if (this.modeledEntity.getBase().getData() instanceof BukkitEntityData data) { + Vector3fc hitboxScale = this.getHitboxScale(); + Hitbox mainHitbox = this.blueprint.getMainHitbox(); + Hitbox scaledHitbox = new Hitbox( + mainHitbox.getWidth() * hitboxScale.x(), + mainHitbox.getHeight() * hitboxScale.y(), + mainHitbox.getDepth() * hitboxScale.z(), + mainHitbox.getEyeHeight() * hitboxScale.y() + ); + data.setHitbox(scaledHitbox); + } + } + } + + @Override + public void tick() { + if (!this.isDestroyed()) { + if (this.modeledEntity.getBase().getData().hasTracking()) { + this.animationHandler.prepare(); + this.forManagers(BehaviorManager::preScriptTick); + this.animationHandler.tickGlobal(); + this.forManagers(BehaviorManager::postScriptTick); + this.forManagers(BehaviorManager::preBoneTick); + this.boneSequencer.reorder(this.roots); + List boneOrders = this.boneSequencer.getBoneOrders(); + int index = 0; + + for (String boneId : boneOrders) { + Map boneMap = this.getBones(); + ActiveModelImpl.ResolvedBoneOrder order = this.resolvedBoneOrder; + if (order == null || order.source() != boneMap || index >= order.ids().length || order.ids()[index] != boneId) { + this.resolvedBoneOrder = order = ActiveModelImpl.ResolvedBoneOrder.resolve(boneMap, boneOrders); + } + + ModelBone bone = order.source() == boneMap && index < order.ids().length && order.ids()[index] == boneId + ? order.bones()[index] + : boneMap.get(boneId); + index++; + if (bone != null) { + bone.tick(); + } + } + + this.forManagers(BehaviorManager::postBoneTick); + this.modelRenderer.readModelData(); + this.wasMarkedHurt = this.isMarkedHurt(); + } else { + this.animationHandler.prepare(); + this.forBones(ModelBone::lazyTick); + this.animationHandler.tickGlobal(); + } + } + } + + @Override + public void destroy() { + this.forBones(ModelBone::destroy); + this.forManagers(BehaviorManager::onDestroy); + this.bones.clear(); + this.boneCache.invalidate(); + this.behaviorManagerCache.invalidate(); + this.behaviorRendererCache.invalidate(); + this.boneSequencer.setDirty(true); + this.getData().markModelGlowing(this, false); + this.modelRenderer.destroy(ModelEngineAPI.getNMSHandler().getGlobalParsers()); + this.destroyed = true; + } + + @Override + public void initializeRenderer() { + if (!this.modelRenderer.isInitialized()) { + this.modelRenderer.initialize(); + } + } + + @Override + public void generateModel() { + if (!this.generated) { + this.generated = true; + + for (Entry entry : this.blueprint.getFlatMap().entrySet()) { + BlueprintBone blueprint = entry.getValue(); + ModelBone parent = blueprint.getParent() == null ? null : this.bones.get(blueprint.getParent().getName()); + ModelBoneImpl bone = new ModelBoneImpl(this, blueprint); + this.configureChildBone(blueprint, parent, bone); + this.bones.put(bone.getUniqueBoneId(), bone); + this.boneCache.invalidate(); + this.behaviorManagerCache.invalidate(); + this.behaviorRendererCache.invalidate(); + this.boneSequencer.setDirty(true); + } + + this.bones.forEach((s, bonex) -> bonex.forBehaviors(BoneBehavior::onModelInitialized)); + if (this.autoRendererInitialization) { + this.modelRenderer.initialize(); + } + } + } + + @Override + public void forceGenerateBone(String parentId, String prefix, final BlueprintBone blueprintBone) { + ModelBone parentBone = parentId == null ? null : this.getBone(parentId).orElse(null); + HashMap forceBoneMap = new HashMap<>(); + var queue = new LinkedList() { + { + this.add(blueprintBone); + } + }; + + while (!queue.isEmpty()) { + BlueprintBone blueprint = queue.pop(); + queue.addAll(blueprint.getChildren().values()); + String name = blueprint.getName(); + String customId = prefix + name; + if (this.bones.containsKey(customId)) { + TLogger.error("Unable to force generate custom bone: ID " + customId + " already exists."); + } else { + ModelBone parent = blueprint.getParent() == null ? parentBone : forceBoneMap.getOrDefault(blueprint.getParent().getName(), parentBone); + ModelBoneImpl bone = new ModelBoneImpl(this, blueprint); + bone.setCustomId(customId); + this.configureChildBone(blueprint, parent, bone); + forceBoneMap.put(name, bone); + this.bones.put(bone.getUniqueBoneId(), bone); + this.boneCache.invalidate(); + this.behaviorManagerCache.invalidate(); + this.behaviorRendererCache.invalidate(); + this.boneSequencer.setDirty(true); + } + } + } + + private void configureChildBone(BlueprintBone blueprint, ModelBone parent, ModelBoneImpl bone) { + if (parent != null) { + bone.setParent(parent); + if (parent.isPivotOverride()) { + bone.setPivot(parent); + } else if (parent.getPivot() != null) { + bone.setPivot(parent.getPivot()); + } + } else { + this.roots.put(bone.getUniqueBoneId(), bone); + } + + for (Entry, BoneBehaviorType.CachedProvider> behaviorEntry : blueprint.getCachedBehaviorProvider().entrySet()) { + BoneBehaviorType type = behaviorEntry.getKey(); + BoneBehaviorType.CachedProvider provider = behaviorEntry.getValue(); + this.getBehaviorManager(type); + this.getBehaviorRenderer(type); + bone.addBoneBehavior(provider.create(bone)); + } + } + + @Override + public void removeBone(String bone) { + ModelBone removed = this.bones.remove(bone); + if (removed != null) { + removed.setParent(null); + this.roots.remove(bone); + this.boneCache.invalidate(); + this.boneSequencer.setDirty(true); + } + } + + @Override + public boolean canHurt() { + return this.canHurt; + } + + @Override + public boolean wasMarkedHurt() { + return this.wasMarkedHurt; + } + + @Override + public boolean isMarkedHurt() { + return this.canHurt && this.modeledEntity != null && this.modeledEntity.getHurtTick() > 0; + } + + @Override + public boolean isGlowing() { + return this.glowing == null ? this.modeledEntity.isGlowing() : this.glowing; + } + + @Override + public void setGlowing(@Nullable Boolean flag) { + this.glowing = flag; + this.getData().markModelGlowing(this, this.glowing != null && this.glowing); + } + + @Override + public int getGlowColor() { + return this.glowColor == null ? this.modeledEntity.getGlowColor() : this.glowColor; + } + + @Override + public Set getGlowAudience() { + return this.glowAudience; + } + + @Override + public boolean isOnFire() { + return this.onFire == null ? this.modeledEntity.getBase().isOnFire() : this.onFire; + } + + @Override + public boolean canRenderFire() { + return this.renderFire == null ? ModelEngineAPI.getConfigCache().isRenderFire() : this.renderFire; + } + + @Override + public float getXHeadRot() { + return this.useLock() ? this.lockedXHeadRot : (this.lockPitch ? 0.0F : this.modeledEntity.getXHeadRot()); + } + + @Override + public float getYHeadRot() { + return this.useLock() ? this.lockedYHeadRot : (this.lockYaw ? this.modeledEntity.getYBodyRot() : this.modeledEntity.getYHeadRot()); + } + + @Override + public float getYBodyRot() { + return this.useLock() ? this.lockedYBodyRot : this.modeledEntity.getYBodyRot(); + } + + private boolean useLock() { + return this.modelRotationLocked != null && this.modelRotationLocked; + } + + @Override + public boolean isModelRotationLocked() { + return this.modelRotationLocked == null ? this.modeledEntity.isModelRotationLocked() : this.modelRotationLocked; + } + + @Override + public void setModelRotationLocked(Boolean flag) { + if (this.modelRotationLocked != flag) { + this.modelRotationLocked = flag; + if (this.modelRotationLocked) { + this.lockedYHeadRot = this.modeledEntity.getYHeadRot(); + this.lockedXHeadRot = this.modeledEntity.getXHeadRot(); + this.lockedYBodyRot = this.modeledEntity.getYBodyRot(); + } + } + } + + @Override + public Optional> getBehaviorManager(BoneBehaviorType type) { + BoneBehaviorType.BehaviorManagerProvider provider = type.getBehaviorManagerProvider(); + if (provider == null) { + return Optional.empty(); + } else { + synchronized (this.behaviorManagers) { + BehaviorManager existing = (BehaviorManager)this.behaviorManagers.get(type); + return existing != null + ? Optional.of(existing) + : Optional.ofNullable((BehaviorManager)this.behaviorManagers.computeIfAbsent(type, boneBehaviorType -> { + BehaviorManager manager = provider.create(this, type); + if (manager == null) { + return null; + } else { + manager.onCreate(); + return manager; + } + })); + } + } + } + + @Override + public Optional getBehaviorRenderer(BoneBehaviorType type) { + synchronized (this.behaviorRenderers) { + BehaviorRenderer renderer = this.behaviorRenderers.get(type); + if (renderer != null) { + return Optional.of(renderer); + } else { + renderer = type.getRenderType().createBehaviorRenderer(this); + if (renderer != null) { + this.behaviorRenderers.put(type, renderer); + } + + return Optional.ofNullable(renderer); + } + } + } + + private void forBones(Consumer consumer) { + for (ModelBone bone : this.roots.values()) { + consumer.accept(bone); + } + } + + private void forManagers(Consumer> consumer) { + synchronized (this.behaviorManagers) { + for (BehaviorManager manager : this.behaviorManagers.values()) { + consumer.accept(manager); + } + } + } + + @Override + public void save(SavedData data) { + data.putString("blueprint", this.blueprint.getName()); + data.putFloat("render_scale", this.getScale().x()); + data.putFloat("hitbox_scale", this.getHitboxScale().x()); + data.putBoolean("can_hurt", this.canHurt()); + data.putInt("default_tint", this.defaultTint.asRGB()); + data.putInt("damage_tint", this.damageTint.asRGB()); + data.putBoolean("lock_pitch", this.lockPitch); + data.putBoolean("lock_yaw", this.lockYaw); + data.putBoolean("hitbox_visible", this.hitboxVisible); + data.putBoolean("shadow_visible", this.shadowVisible); + data.putBoolean("main_hitbox", this.mainHitbox); + data.putBoolean("glowing", this.glowing); + data.putInt("glow_color", this.glowColor); + data.putInt("block_light", this.blockLight); + data.putInt("sky_light", this.skyLight); + HashSet removed = new HashSet<>(); + SavedData boneDataMap = new SavedData(); + + for (String boneId : this.blueprint.getFlatMap().keySet()) { + ModelBone bone = this.bones.get(boneId); + if (bone == null) { + removed.add(boneId); + } else { + bone.save().ifPresent(boneData -> boneDataMap.putData(boneId, boneData)); + } + } + + data.putList("removed", removed); + data.putData("default_bones", boneDataMap); + this.animationHandler.save().ifPresent(animationData -> data.putData("animation_handler", animationData)); + Map, BehaviorManager> managers = this.getBehaviorManagers(); + if (!managers.isEmpty()) { + SavedData managerData = new SavedData(); + managers.forEach((boneBehaviorType, manager) -> manager.save().ifPresent(savedData -> managerData.putData(boneBehaviorType.getId(), savedData))); + data.putData("managers", managerData); + } + + Map, BehaviorRenderer> renderers = this.getBehaviorRenderers(); + if (!renderers.isEmpty()) { + SavedData rendererData = new SavedData(); + renderers.forEach((boneBehaviorType, renderer) -> renderer.save().ifPresent(savedData -> rendererData.putData(boneBehaviorType.getId(), savedData))); + data.putData("renderers", rendererData); + } + } + + @Override + public void load(SavedData data) { + this.setScale(data.getFloat("render_scale").floatValue()); + this.setHitboxScale(data.getFloat("hitbox_scale").floatValue()); + this.setCanHurt(data.getBoolean("can_hurt")); + this.setDefaultTint(Color.fromRGB(data.getInt("default_tint"))); + this.setDamageTint(Color.fromRGB(data.getInt("damage_tint"))); + this.setLockPitch(data.getBoolean("lock_pitch")); + this.setLockYaw(data.getBoolean("lock_yaw")); + this.setHitboxVisible(data.getBoolean("hitbox_visible")); + this.setShadowVisible(data.getBoolean("shadow_visible")); + this.setGlowing(data.getBoolean("glowing")); + this.setGlowColor(data.getInt("glow_color")); + this.setBlockLight(data.getInt("block_light", -1)); + this.setSkyLight(data.getInt("sky_light", -1)); + + for (Object remove : data.getList("removed")) { + this.removeBone((String)remove); + } + + data.getData("default_bones").ifPresent(boneDataMap -> { + for (String key : boneDataMap.keySet()) { + this.getBone(key).ifPresent(modelBone -> boneDataMap.getData(key).ifPresent(modelBone::load)); + } + }); + Optional managerData = data.getData("managers"); + managerData.ifPresent( + savedData -> this.getBehaviorManagers().forEach((boneBehaviorType, manager) -> savedData.getData(boneBehaviorType.getId()).ifPresent(manager::load)) + ); + Optional renderersData = data.getData("renderers"); + renderersData.ifPresent( + savedData -> this.getBehaviorRenderers() + .forEach((boneBehaviorType, renderer) -> savedData.getData(boneBehaviorType.getId()).ifPresent(renderer::load)) + ); + } + + private IEntityData getData() { + return this.modeledEntity.getBase().getData(); + } + + @Override + public ModelBlueprint getBlueprint() { + return this.blueprint; + } + + @Override + public MetadataRegistry getMetadata() { + return this.metadata; + } + + @Override + public ModelRenderer getModelRenderer() { + return this.modelRenderer; + } + + @Override + public AnimationHandler getAnimationHandler() { + return this.animationHandler; + } + + public CachedImmutableMap getBoneCache() { + return this.boneCache; + } + + public CachedImmutableMap, BehaviorManager> getBehaviorManagerCache() { + return this.behaviorManagerCache; + } + + public CachedImmutableMap, BehaviorRenderer> getBehaviorRendererCache() { + return this.behaviorRendererCache; + } + + @Override + public ModeledEntity getModeledEntity() { + return this.modeledEntity; + } + + @Override + public boolean isMainHitbox() { + return this.mainHitbox; + } + + public boolean isGenerated() { + return this.generated; + } + + @Override + public boolean isDestroyed() { + return this.destroyed; + } + + @Override + public boolean isRemoved() { + return this.removed; + } + + public boolean isAutoRendererInitialization() { + return this.autoRendererInitialization; + } + + @Override + public boolean isHitboxVisible() { + return this.hitboxVisible; + } + + @Override + public boolean isShadowVisible() { + return this.shadowVisible; + } + + @Override + public float getViewRange() { + return this.viewRange; + } + + public boolean isCanHurt() { + return this.canHurt; + } + + @Override + public Color getDefaultTint() { + return this.defaultTint; + } + + @Override + public Color getDamageTint() { + return this.damageTint; + } + + public boolean isWasMarkedHurt() { + return this.wasMarkedHurt; + } + + @Override + public int getBlockLight() { + return this.blockLight; + } + + @Override + public int getSkyLight() { + return this.skyLight; + } + + @Override + public Billboard getBillboard() { + return this.billboard; + } + + @Override + public boolean isLockPitch() { + return this.lockPitch; + } + + @Override + public boolean isLockYaw() { + return this.lockYaw; + } + + @Override + public float getLockedYHeadRot() { + return this.lockedYHeadRot; + } + + @Override + public float getLockedXHeadRot() { + return this.lockedXHeadRot; + } + + @Override + public float getLockedYBodyRot() { + return this.lockedYBodyRot; + } + + @Override + public boolean isInvisUpdate() { + return this.invisUpdate; + } + + @Override + public boolean isCameraPivot() { + return this.cameraPivot; + } + + public BoneSequencer getBoneSequencer() { + return this.boneSequencer; + } + + @Override + public Callback getScaleCallback() { + return this.scaleCallback; + } + + @Override + public Callback getPreSendCallback() { + return this.preSendCallback; + } + + @Override + public Callback getPostSendCallback() { + return this.postSendCallback; + } + + @Override + public void setModeledEntity(ModeledEntity modeledEntity) { + this.modeledEntity = modeledEntity; + } + + @Override + public void setMainHitbox(boolean mainHitbox) { + this.mainHitbox = mainHitbox; + } + + @Override + public void setRemoved(boolean removed) { + this.removed = removed; + } + + @Override + public void setAutoRendererInitialization(boolean autoRendererInitialization) { + this.autoRendererInitialization = autoRendererInitialization; + } + + @Override + public void setHitboxVisible(boolean hitboxVisible) { + this.hitboxVisible = hitboxVisible; + } + + @Override + public void setShadowVisible(boolean shadowVisible) { + this.shadowVisible = shadowVisible; + } + + @Override + public void setViewRange(float viewRange) { + this.viewRange = viewRange; + } + + @Override + public void setCanHurt(boolean canHurt) { + this.canHurt = canHurt; + } + + @Override + public void setDefaultTint(Color defaultTint) { + this.defaultTint = defaultTint; + } + + @Override + public void setDamageTint(Color damageTint) { + this.damageTint = damageTint; + } + + @Override + public void setGlowColor(Integer glowColor) { + this.glowColor = glowColor; + } + + @Override + public void setGlowAudience(Set glowAudience) { + this.glowAudience = glowAudience; + } + + @Override + public void setBlockLight(int blockLight) { + this.blockLight = blockLight; + } + + @Override + public void setSkyLight(int skyLight) { + this.skyLight = skyLight; + } + + @Override + public void setBillboard(Billboard billboard) { + this.billboard = billboard; + } + + @Override + public void setOnFire(Boolean onFire) { + this.onFire = onFire; + } + + @Override + public void setRenderFire(Boolean renderFire) { + this.renderFire = renderFire; + } + + @Override + public void setLockPitch(boolean lockPitch) { + this.lockPitch = lockPitch; + } + + @Override + public void setLockYaw(boolean lockYaw) { + this.lockYaw = lockYaw; + } + + @Override + public void setLockedYHeadRot(float lockedYHeadRot) { + this.lockedYHeadRot = lockedYHeadRot; + } + + @Override + public void setLockedXHeadRot(float lockedXHeadRot) { + this.lockedXHeadRot = lockedXHeadRot; + } + + @Override + public void setLockedYBodyRot(float lockedYBodyRot) { + this.lockedYBodyRot = lockedYBodyRot; + } + + @Override + public void setInvisUpdate(boolean invisUpdate) { + this.invisUpdate = invisUpdate; + } + + @Override + public void setCameraPivot(boolean cameraPivot) { + this.cameraPivot = cameraPivot; + } + + private record ResolvedBoneOrder(Map source, String[] ids, ModelBone[] bones) { + private static ActiveModelImpl.ResolvedBoneOrder resolve(Map source, List boneOrders) { + String[] ids = boneOrders.toArray(new String[0]); + ModelBone[] bones = new ModelBone[ids.length]; + + for (int i = 0; i < ids.length; i++) { + bones[i] = source.get(ids[i]); + } + + return new ActiveModelImpl.ResolvedBoneOrder(source, ids, bones); + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/BoneSequencer.java b/core/src/main/java/com/ticxo/modelengine/core/model/BoneSequencer.java new file mode 100644 index 0000000..f871048 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/BoneSequencer.java @@ -0,0 +1,48 @@ +package com.ticxo.modelengine.core.model; + +import com.ticxo.modelengine.api.model.bone.ModelBone; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class BoneSequencer { + private final Set processedBones = new HashSet<>(); + private final List boneOrders = new ArrayList<>(); + private volatile boolean dirty = true; + + protected void reorder(Map roots) { + if (this.dirty) { + this.dirty = false; + this.processedBones.clear(); + this.boneOrders.clear(); + + int size; + do { + size = this.boneOrders.size(); + this.order(roots); + } while (size != this.boneOrders.size()); + } + } + + private void order(Map roots) { + for (ModelBone bone : roots.values()) { + if (this.processedBones.contains(bone.getBoneId())) { + this.order(bone.getChildren()); + } else if (bone.getTickDependencies().isEmpty() || this.processedBones.containsAll(bone.getTickDependencies())) { + this.boneOrders.add(bone.getBoneId()); + this.processedBones.add(bone.getBoneId()); + this.order(bone.getChildren()); + } + } + } + + public List getBoneOrders() { + return this.boneOrders; + } + + public void setDirty(boolean dirty) { + this.dirty = dirty; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/ModeledEntityImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/ModeledEntityImpl.java new file mode 100644 index 0000000..c3664cb --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/ModeledEntityImpl.java @@ -0,0 +1,624 @@ +package com.ticxo.modelengine.core.model; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionHandler; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.events.AddModelEvent; +import com.ticxo.modelengine.api.events.ModelSetupEvent; +import com.ticxo.modelengine.api.events.RemoveModelEvent; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.callback.Callback; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import com.ticxo.modelengine.api.utils.data.tracker.FloatDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.meta.MetadataRegistry; +import com.ticxo.modelengine.core.model.bone.manager.MountDataImpl; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3fc; + +public class ModeledEntityImpl implements ModeledEntity { + private final BaseEntity base; + private final MetadataRegistry metadata = new MetadataRegistry(); + private final AnimationLODHandler animationLodHandler; + private final Map models = Maps.newConcurrentMap(); + private final Map, GlobalBehaviorData> data = Maps.newConcurrentMap(); + private final Map>> tickTasks = Maps.newConcurrentMap(); + private final Callback destroyCallback = new Callback<>(runs -> () -> runs.forEach(Runnable::run)); + private volatile Map cachedModels; + private final boolean initialized; + private final List queuedTask = new ArrayList<>(); + private final FloatDataTracker trueYHeadRot = new FloatDataTracker(0.0F); + private final FloatDataTracker trueXHeadRot = new FloatDataTracker(0.0F); + private final FloatDataTracker trueYBodyRot = new FloatDataTracker(0.0F); + private final RootMotionHandler rootMotionHandler = new RootMotionHandler(this); + private int tick; + private boolean isBaseEntityVisible = true; + private boolean destroyed; + private boolean removed; + private int hurtTick = 0; + private boolean isModelRotationLocked; + private int rotationTick = -1; + private float yHeadRot = 0.0F; + private float xHeadRot = 0.0F; + private float yBodyRot = 0.0F; + private boolean shouldSave = true; + private volatile String cachedSaveJson; + private ActiveModel lastHitboxOverride = null; + + public ModeledEntityImpl(@NotNull BaseEntity base, @Nullable Consumer consumer) { + this.base = base; + this.animationLodHandler = new AnimationLODHandler(this); + if (consumer != null) { + consumer.accept(this); + } + + synchronized (this.queuedTask) { + this.queuedTask.forEach(Runnable::run); + this.initialized = true; + } + + this.registerSelf(); + } + + @Override + public boolean tick() { + if (!this.initialized) { + return true; + } else { + if (this.hurtTick > 0) { + this.hurtTick--; + } + + if (this.base.isAlive()) { + if (!this.isModelRotationLocked) { + BodyRotationController bodyRotationController = this.base.getBodyRotationController(); + bodyRotationController.tick(); + this.trueYHeadRot.set(bodyRotationController.getYHeadRot()); + this.trueXHeadRot.set(bodyRotationController.getXHeadRot()); + this.trueYBodyRot.set(bodyRotationController.getYBodyRot()); + } + + if (this.rotationTick == -1) { + this.yHeadRot = this.trueYHeadRot.get(); + this.xHeadRot = this.trueXHeadRot.get(); + this.yBodyRot = this.trueYBodyRot.get(); + this.trueYHeadRot.clearDirty(); + this.trueXHeadRot.clearDirty(); + this.trueYBodyRot.clearDirty(); + this.rotationTick = 0; + } + + if (!this.base.isWalking()) { + this.yBodyRot = this.trueYBodyRot.get(); + } + + if (this.trueYHeadRot.isDirty() || this.trueXHeadRot.isDirty() || this.trueYBodyRot.isDirty()) { + this.rotationTick = 3; + this.trueYHeadRot.clearDirty(); + this.trueXHeadRot.clearDirty(); + this.trueYBodyRot.clearDirty(); + } + + if (this.rotationTick > 0) { + this.yHeadRot = TMath.rotLerp(this.yHeadRot, this.trueYHeadRot.get(), (double)(1.0F / this.rotationTick)); + this.xHeadRot = TMath.rotLerp(this.xHeadRot, this.trueXHeadRot.get(), (double)(1.0F / this.rotationTick)); + this.yBodyRot = TMath.rotLerp(this.yBodyRot, this.trueYBodyRot.get(), (double)(1.0F / this.rotationTick)); + this.rotationTick--; + } + } + + this.validateYaws(); + this.tick++; + if (this.removed || this.base.isRemoved()) { + return false; + } else if (this.base.isAlive()) { + for (ActiveModel model : this.models.values()) { + model.tick(); + } + + return true; + } else { + boolean hasFinished = true; + + for (ActiveModel model : this.models.values()) { + model.tick(); + if (hasFinished) { + hasFinished = model.getAnimationHandler().hasFinishedAllAnimations(); + } + } + + this.base.setForcedAlive(!hasFinished); + return !hasFinished && !this.base.getData().getTracking().isEmpty(); + } + } + } + + private void validateYaws() { + if (Float.isNaN(this.trueYHeadRot.get())) { + this.trueYHeadRot.set(0.0F); + } + + if (Float.isNaN(this.trueXHeadRot.get())) { + this.trueXHeadRot.set(0.0F); + } + + if (Float.isNaN(this.trueYBodyRot.get())) { + this.trueYBodyRot.set(0.0F); + } + + this.yHeadRot = Float.isNaN(this.yHeadRot) ? 0.0F : this.yHeadRot; + this.xHeadRot = Float.isNaN(this.xHeadRot) ? 0.0F : this.xHeadRot; + this.yBodyRot = Float.isNaN(this.yBodyRot) ? 0.0F : this.yBodyRot; + } + + @Override + public void destroy() { + this.destroyCallback.invoker().run(); + this.destroyed = true; + this.animationLodHandler.destroy(); + this.models.forEach((s, model) -> model.destroy()); + this.models.clear(); + this.cachedModels = null; + if (this.base.getOriginal() instanceof Entity entity && !(entity instanceof Player)) { + ModelEngineAPI.getPivotOverrideRegistry().remove(entity.getUniqueId()); + } + } + + @Override + public void markRemoved() { + this.removed = true; + } + + @Override + public void restore() { + this.removed = false; + } + + @Override + public void queuePostInitTask(Runnable runnable) { + synchronized (this.queuedTask) { + if (this.initialized) { + runnable.run(); + } else { + this.queuedTask.add(runnable); + } + } + } + + @Override + public void setBaseEntityVisible(boolean flag) { + if (this.isBaseEntityVisible() != flag) { + this.isBaseEntityVisible = flag; + this.base.setVisible(this.isBaseEntityVisible); + } + } + + @Override + public void markHurt() { + this.hurtTick = 10; + } + + @Override + public boolean shouldBeSaved() { + return this.shouldSave; + } + + @Override + public void setSaved(boolean flag) { + this.shouldSave = flag; + } + + @Override + public String getCachedSaveJson() { + return this.cachedSaveJson; + } + + @Override + public void updateSaveCache() { + try { + this.save().ifPresentOrElse(data -> this.cachedSaveJson = data.toString(), () -> this.cachedSaveJson = null); + } catch (Throwable var2) { + } + } + + @Override + public boolean isGlowing() { + return this.base.isGlowing(); + } + + @Override + public int getGlowColor() { + return this.base.getGlowColor(); + } + + @Override + public void setYHeadRot(float rotation) { + this.trueYHeadRot.set(rotation); + } + + @Override + public void setXHeadRot(float rotation) { + this.trueXHeadRot.set(rotation); + } + + @Override + public void setYBodyRot(float rotation) { + this.trueYBodyRot.set(rotation); + } + + @Override + public void setYHeadRotImmediately(float rotation) { + this.trueYHeadRot.set(rotation); + this.yHeadRot = rotation; + } + + @Override + public void setXHeadRotImmediately(float rotation) { + this.trueXHeadRot.set(rotation); + this.xHeadRot = rotation; + } + + @Override + public void setYBodyRotImmediately(float rotation) { + this.trueYBodyRot.set(rotation); + this.yBodyRot = rotation; + } + + @Override + public void setRotationTick(int rotationTick) { + this.rotationTick = rotationTick; + } + + @Override + public Optional addModel(@NotNull ActiveModel model, boolean overrideHitbox) { + assert !this.isDestroyed() : "Modeled Entity has been destroyed!"; + + assert model.getModeledEntity() == null || model.isRemoved() : "Active Model already belongs to a different Modeled Entity"; + + AddModelEvent event = new AddModelEvent(this, model); + event.setOverrideHitbox(overrideHitbox); + ModelEngineAPI.callEvent(event); + if (event.isCancelled()) { + return Optional.empty(); + } else { + model.setRemoved(false); + model.setModeledEntity(this); + model.generateModel(); + Optional previous = this.removeModel(model.getBlueprint().getName()); + this.models.put(model.getBlueprint().getName(), model); + this.cachedModels = null; + model.getMountManager().ifPresent(mountManager -> { + GlobalBehaviorData mountData = this.getMountData(); + if (((MountData)mountData).getMainMountManager() == null) { + ((MountData)mountData).setMainMountManager(mountManager); + } + }); + if (overrideHitbox) { + if (this.lastHitboxOverride != null) { + this.lastHitboxOverride.setMainHitbox(false); + } + + model.setMainHitbox(true); + this.lastHitboxOverride = model; + Hitbox mainHitbox = model.getBlueprint().getMainHitbox(); + Vector3fc scale = model.getScale(); + Hitbox scaledRenderHitbox = new Hitbox( + mainHitbox.getWidth() * scale.x(), mainHitbox.getHeight() * scale.y(), mainHitbox.getDepth() * scale.z(), mainHitbox.getEyeHeight() * scale.y() + ); + this.base.getData().setCullHitbox(scaledRenderHitbox); + if (this.base.getData() instanceof BukkitEntityData data) { + Vector3fc hitboxScale = model.getHitboxScale(); + Hitbox scaledHitbox = new Hitbox( + mainHitbox.getWidth() * hitboxScale.x(), + mainHitbox.getHeight() * hitboxScale.y(), + mainHitbox.getDepth() * hitboxScale.z(), + mainHitbox.getEyeHeight() * hitboxScale.y() + ); + data.setHitbox(scaledHitbox); + } + } + + ModelEngineAPI.callEvent(new ModelSetupEvent(this, model)); + return previous; + } + } + + @Override + public Optional removeModel(String id) { + assert !this.isDestroyed() : "Modeled Entity has been destroyed!"; + + ActiveModel model = this.models.get(id); + if (model == null) { + return Optional.empty(); + } else { + RemoveModelEvent event = new RemoveModelEvent(this, model); + ModelEngineAPI.callEvent(event); + if (event.isCancelled()) { + return Optional.empty(); + } else { + this.models.remove(id); + this.cachedModels = null; + model.setRemoved(true); + return Optional.of(model); + } + } + } + + @Override + public Optional getModel(@Nullable String id) { + return Optional.ofNullable(id == null ? null : this.models.get(id)); + } + + @Override + public Map getModels() { + if (this.cachedModels == null) { + this.cachedModels = ImmutableMap.copyOf(this.models); + } + + return this.cachedModels; + } + + @Override + public GlobalBehaviorData getOrCreateGlobalBehaviorData(BoneBehaviorType type, Supplier supplier) { + GlobalBehaviorData existing = this.data.get(type); + return existing != null ? existing : this.data.computeIfAbsent(type, boneBehaviorType -> supplier.get()); + } + + @Override + public GlobalBehaviorData getGlobalBehaviorData(BoneBehaviorType type) { + return this.data.get(type); + } + + @Override + public GlobalBehaviorData removeGlobalBehaviorData(BoneBehaviorType type) { + return this.data.remove(type); + } + + @Override + public Map, GlobalBehaviorData> getAllGlobalBehaviorData(BoneBehaviorType type) { + return ImmutableMap.copyOf(this.data); + } + + @Override + public T getMountData() { + return (T)this.getOrCreateGlobalBehaviorData(BoneBehaviorTypes.MOUNT, MountDataImpl::new); + } + + @Override + public boolean isPivotOverride(int id) { + return this.models.values().stream().anyMatch(model -> model.getPivotOverride().map(override -> override.getId() == id).orElse(false)); + } + + @Override + public UUID registerTickTask(ModeledEntity.Phase phase, Function function) { + UUID uuid = UUID.randomUUID(); + this.tickTasks.computeIfAbsent(phase, phase1 -> Maps.newConcurrentMap()).put(uuid, function); + return uuid; + } + + @Override + public UUID registerTickTask(ModeledEntity.Phase phase, Consumer consumer) { + return this.registerTickTask(phase, modeledEntity -> { + consumer.accept(modeledEntity); + return false; + }); + } + + @Override + public void removeTickTask(UUID uuid) { + for (Entry>> entry : this.tickTasks.entrySet()) { + if (entry.getValue().remove(uuid) != null) { + return; + } + } + } + + @Override + public void runTickTasks(ModeledEntity.Phase phase) { + Map> tasks = this.tickTasks.get(phase); + if (tasks != null) { + HashSet remover = null; + + for (Entry> entry : tasks.entrySet()) { + if (entry.getValue().apply(this)) { + if (remover == null) { + remover = new HashSet<>(); + } + + remover.add(entry.getKey()); + } + } + + if (remover != null) { + remover.forEach(tasks::remove); + } + } + } + + @Override + public void save(SavedData data) { + data.putString("version", "R4.0.3"); + data.putBoolean("base_visible", this.isBaseEntityVisible()); + data.putBoolean("rotation_locked", this.isModelRotationLocked()); + data.putFloat("head_y", this.trueYHeadRot.get()); + data.putFloat("head_x", this.trueXHeadRot.get()); + data.putFloat("body_y", this.trueYBodyRot.get()); + ArrayList list = new ArrayList<>(); + + for (ActiveModel activeModel : this.models.values()) { + activeModel.save().ifPresent(list::add); + } + + data.putList("models", list); + this.base.save().ifPresent(entityData -> data.putData("base_entity", entityData)); + } + + @Override + public void load(SavedData data) { + this.setBaseEntityVisible(data.getBoolean("base_visible")); + this.setModelRotationLocked(data.getBoolean("rotation_locked")); + this.trueYHeadRot.set(this.yHeadRot = data.getFloat("head_y", 0.0F)); + this.trueXHeadRot.set(this.xHeadRot = data.getFloat("head_x", 0.0F)); + this.trueYBodyRot.set(this.yBodyRot = data.getFloat("body_y", 0.0F)); + this.trueYHeadRot.clearDirty(); + this.trueXHeadRot.clearDirty(); + this.trueYBodyRot.clearDirty(); + this.base.getBodyRotationController().setYBodyRot(this.yBodyRot); + + for (SavedData modelData : data.getList("models", SavedData.class)) { + ActiveModel model = ActiveModelImpl.fromData(modelData); + if (model != null) { + model.setAutoRendererInitialization(false); + this.addModel(model, model.isMainHitbox()).ifPresent(ActiveModel::destroy); + model.load(modelData); + model.initializeRenderer(); + } + } + + data.getData("base_entity").ifPresent(this.base::load); + } + + @Override + public BaseEntity getBase() { + return this.base; + } + + @Override + public MetadataRegistry getMetadata() { + return this.metadata; + } + + @Override + public AnimationLODHandler getAnimationLodHandler() { + return this.animationLodHandler; + } + + public Map, GlobalBehaviorData> getData() { + return this.data; + } + + public Map>> getTickTasks() { + return this.tickTasks; + } + + @Override + public Callback getDestroyCallback() { + return this.destroyCallback; + } + + public Map getCachedModels() { + return this.cachedModels; + } + + @Override + public boolean isInitialized() { + return this.initialized; + } + + public List getQueuedTask() { + return this.queuedTask; + } + + public FloatDataTracker getTrueYHeadRot() { + return this.trueYHeadRot; + } + + public FloatDataTracker getTrueXHeadRot() { + return this.trueXHeadRot; + } + + public FloatDataTracker getTrueYBodyRot() { + return this.trueYBodyRot; + } + + @Override + public RootMotionHandler getRootMotionHandler() { + return this.rootMotionHandler; + } + + @Override + public int getTick() { + return this.tick; + } + + @Override + public boolean isBaseEntityVisible() { + return this.isBaseEntityVisible; + } + + @Override + public boolean isDestroyed() { + return this.destroyed; + } + + public boolean isRemoved() { + return this.removed; + } + + @Override + public int getHurtTick() { + return this.hurtTick; + } + + @Override + public boolean isModelRotationLocked() { + return this.isModelRotationLocked; + } + + public int getRotationTick() { + return this.rotationTick; + } + + @Override + public float getYHeadRot() { + return this.yHeadRot; + } + + @Override + public float getXHeadRot() { + return this.xHeadRot; + } + + @Override + public float getYBodyRot() { + return this.yBodyRot; + } + + public boolean isShouldSave() { + return this.shouldSave; + } + + public ActiveModel getLastHitboxOverride() { + return this.lastHitboxOverride; + } + + @Override + public void setModelRotationLocked(boolean isModelRotationLocked) { + this.isModelRotationLocked = isModelRotationLocked; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/ModelBoneImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/ModelBoneImpl.java new file mode 100644 index 0000000..fcb1625 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/ModelBoneImpl.java @@ -0,0 +1,1186 @@ +package com.ticxo.modelengine.core.model.bone; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.property.SubTickProperty; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotion; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.BoneItems; +import com.ticxo.modelengine.api.model.bone.ManualAnimator; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.behavior.ProceduralType; +import com.ticxo.modelengine.api.utils.OffsetMode; +import com.ticxo.modelengine.api.utils.StepFlag; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.MapDataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker; +import com.ticxo.modelengine.api.utils.math.SafeTransform; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.math.Transform; +import com.ticxo.modelengine.core.misc.Cardinal; +import com.ticxo.modelengine.core.model.ActiveModelImpl; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Consumer; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Display.Billboard; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Transformation; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class ModelBoneImpl implements ModelBone { + @NotNull + private final ActiveModel activeModel; + @NotNull + private final BlueprintBone blueprintBone; + private final Map children = Maps.newConcurrentMap(); + private final Map, BoneBehavior> boneBehaviors = new LinkedHashMap<>(); + private BoneBehavior[] boneBehaviorsArray = new BoneBehavior[0]; + private final BoneItems itemModels = new BoneItems(); + private final DataTracker modelScale = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final Set proceduralTypes = new HashSet<>(); + private boolean proceduralAnimation; + private boolean proceduralTransform; + private ManualAnimator manualAnimator; + private final SafeTransform localTransform = new SafeTransform(); + private final SafeTransform globalTransform = new SafeTransform(); + private final Matrix4f transformMatrix = new Matrix4f(); + private final Map stepFlags = new HashMap<>(); + private final DataTracker> trackedStepFlags = new MapDataTracker<>(new HashMap<>()); + private final Set tickDependencies = new HashSet<>(); + private volatile ModelBoneImpl.SubTicks subTicks; + private String customId = null; + @Nullable + private ModelBone parent; + @Nullable + private ModelBone pivot; + private boolean pivotOverride; + private Location pivotLocation; + private boolean isRenderer; + private float yaw; + private boolean hasGlobalRotation; + private Color lastColor; + private Color defaultTint; + private Color damageTint; + private boolean enchanted; + private Boolean glowing; + private Integer glowColor; + private Set glowAudience; + private int blockLight = -1; + private int skyLight = -1; + private Billboard billboard; + private boolean visible = true; + private boolean scaleHidden; + private boolean scaleStepped; + private boolean markedDestroy; + private boolean isBoneOnGround; + + public ModelBoneImpl(@NotNull ActiveModel activeModel, @NotNull BlueprintBone blueprintBone) { + this.activeModel = activeModel; + this.blueprintBone = blueprintBone; + this.updateYaw(); + this.globalTransform.setPosition(blueprintBone.getRotatedGlobalPosition()); + this.globalTransform.setLeftQuaternion(blueprintBone.getGlobalQuaternion()); + this.modelScale.set(new Vector3f(blueprintBone.getModelScale()).mul(blueprintBone.getScale())); + this.globalTransform.setScale(this.modelScale.get()); + this.isRenderer = blueprintBone.isRenderer(); + if (this.isRenderer) { + this.setModel(blueprintBone); + } else { + BlueprintBone dupeTarget = blueprintBone.getDupeTarget(); + if (dupeTarget != null && dupeTarget.isRenderer()) { + this.setModel(dupeTarget); + this.isRenderer = true; + } + } + + this.setVisible(blueprintBone.isRenderByDefault()); + this.globalTransform.recordLast(); + this.globalTransform.recordSafe(); + this.localTransform.setPosition(blueprintBone.getLocalPosition()); + this.localTransform.setLeftEuler(blueprintBone.getLocalRotation()); + this.localTransform.recordLast(); + this.localTransform.recordSafe(); + } + + @Override + public String getUniqueBoneId() { + return this.getCustomId() == null ? this.getBoneId() : this.getCustomId(); + } + + @Override + public String getBoneId() { + return this.blueprintBone.getName(); + } + + @Override + public void setParent(@Nullable ModelBone bone) { + if (this.parent != null) { + this.parent.getChildren().remove(this.getUniqueBoneId()); + } + + this.parent = bone; + if (this.parent != null) { + this.parent.getChildren().put(this.getUniqueBoneId(), this); + } + + this.forBehaviors(boneBehavior -> boneBehavior.onParentSwap(this.parent)); + if (this.activeModel instanceof ActiveModelImpl impl) { + impl.getBoneSequencer().setDirty(true); + } + } + + @Override + public Location calculatePivotLocation() { + if (this.pivot != null) { + Location loc = this.pivot.getPivotLocation(); + if (loc != null) { + return loc.clone(); + } + } + + return this.getBaseLocation(); + } + + @Override + public Location getBaseLocation() { + return this.activeModel.getModeledEntity().getBase().getLocation().clone(); + } + + @Override + public void addTickDependencies(String... boneIds) { + this.tickDependencies.addAll(Arrays.asList(boneIds)); + if (this.activeModel instanceof ActiveModelImpl impl) { + impl.getBoneSequencer().setDirty(true); + } + } + + @Override + public void removeTickDependencies(String... boneIds) { + for (String id : boneIds) { + this.tickDependencies.remove(id); + } + + if (this.activeModel instanceof ActiveModelImpl impl) { + impl.getBoneSequencer().setDirty(true); + } + } + + @Override + public void clearTickDependencies() { + this.tickDependencies.clear(); + if (this.activeModel instanceof ActiveModelImpl impl) { + impl.getBoneSequencer().setDirty(true); + } + } + + @Override + public void tick() { + this.stepFlags.clear(); + this.trackedStepFlags.clearDirty(); + this.scaleStepped = false; + this.localTransform.recordLast(); + this.globalTransform.recordLast(); + this.tryTintModel(); + this.localTransform.identity(); + if (this.manualAnimator == null || this.manualAnimator.applyBoneDefaultLocal()) { + this.localTransform.setPosition(this.blueprintBone.getLocalPosition()); + this.localTransform.setLeftEuler(this.blueprintBone.getLocalRotation()); + } + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.preAnimation(); + } + + if (this.manualAnimator == null) { + if (this.proceduralAnimation) { + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.onAnimation(); + } + } else { + this.activeModel.getAnimationHandler().updateBone(this); + } + } else { + this.manualAnimator.animate(this); + } + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.postAnimation(); + } + + boolean ownScaleHidden = this.scaleStepped && this.localTransform.getScale().lengthSquared() < 1.0E-5F; + this.scaleHidden = ownScaleHidden || this.parent != null && this.parent.isScaleHidden(); + if (this.scaleHidden) { + this.localTransform.setScale(this.localTransform.getLastScale()); + } + + this.localTransform.recordSafe(); + this.updateYaw(); + if (this.proceduralTransform) { + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.onGlobalCalculation(); + } + } else { + this.calculateGlobalTransform(); + } + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.preTransformDecompose(); + } + + this.decomposeTransform(); + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.postTransformDecompose(); + } + + this.recomposeTransform(); + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.postTransformRecompose(); + } + + this.globalTransform.mutateScale(scale -> scale.mul((Vector3fc)this.modelScale.get()).mul(this.activeModel.getScale())); + this.globalTransform.mutatePosition(position -> position.mul(this.activeModel.getScale())); + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.onFinalize(); + } + + if (this.isRootBone()) { + Vector3f pos = this.localTransform.getSafePosition(); + if (!TMath.isSimilar(pos.lengthSquared(), 0.0F)) { + this.queueVelocity(new RootMotion(pos, this.activeModel.getYHeadRot(), this.isBoneOnGround)); + } + + this.globalTransform.mutatePosition(Vector3f::zero); + } + + this.trackedStepFlags.set(this.stepFlags); + this.globalTransform.recordSafe(); + this.captureSubTicks(); + } + + @Override + public void lazyTick() { + this.updateYaw(); + if (!this.children.isEmpty()) { + this.children.values().forEach(ModelBone::lazyTick); + } + } + + private void updateYaw() { + this.yaw = this.pivot == null ? this.activeModel.getYBodyRot() : this.pivot.getYaw(); + + for (int i = 0; i < this.boneBehaviorsArray.length; i++) { + this.yaw = this.boneBehaviorsArray[i].onUpdateYaw(this.yaw); + } + + this.yaw = Float.isNaN(this.yaw) ? 0.0F : TMath.wrapDegree(this.yaw); + } + + @Override + public void destroy() { + this.markedDestroy = true; + this.boneBehaviors.values().forEach(BoneBehavior::onRemove); + this.children.values().forEach(ModelBone::destroy); + this.children.clear(); + this.getData().markBoneGlowing(this, false); + if (this.parent != null && !this.parent.isMarkedDestroy()) { + this.parent.getChildren().remove(this.getUniqueBoneId()); + } + + this.activeModel.removeBone(this.getUniqueBoneId()); + } + + @Override + public void setModelScale(int scale) { + this.modelScale.set(new Vector3f(scale)); + } + + @Override + public void calculateGlobalTransform() { + this.transformMatrix.identity(); + if (this.parent != null) { + this.transformMatrix.set(this.parent.getTransformMatrix()); + } + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.preGlobalCalculation(); + } + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.preGlobalTranslate(); + } + + this.transformMatrix.translate(this.localTransform.getPosition()); + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.postGlobalTranslate(); + } + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.preGlobalRotate(); + } + + if (this.parent != null && this.hasGlobalRotation) { + this.transformMatrix.rotate(this.parent.getGlobalTransform().getLeftQuaternion().invert(new Quaternionf())); + } + + this.transformMatrix.rotate(this.localTransform.getLeftQuaternion()); + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.postGlobalRotate(); + } + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.preGlobalScale(); + } + + TMath.clampedScale(this.transformMatrix, this.localTransform.getScale()); + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.postGlobalScale(); + } + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.preGlobalShear(); + } + + this.transformMatrix.rotate(this.localTransform.getRightQuaternion()); + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.postGlobalShear(); + } + + for (BoneBehavior behavior : this.boneBehaviorsArray) { + behavior.postGlobalCalculation(); + } + } + + @Override + public boolean hasGlobalRotation() { + return this.hasGlobalRotation; + } + + private void decomposeTransform() { + decomposeInto(this.transformMatrix, this.globalTransform); + } + + private static void decomposeInto(Matrix4f matrix, Transform target) { + Transformation t = ModelEngineAPI.getNMSHandler().decompose(matrix); + Triple correct = Triple.of(t.getLeftRotation(), t.getScale(), t.getRightRotation()); + Vector3f delta = target.getRightQuaternion().difference(t.getRightRotation()).getEulerAnglesXYZ(new Vector3f()); + if (Math.abs(delta.x) >= (float) (Math.PI / 4) || Math.abs(delta.y) >= (float) (Math.PI / 4) || Math.abs(delta.z) >= (float) (Math.PI / 4)) { + float len = Float.MAX_VALUE; + + for (Cardinal cardinal : Cardinal.cardinals()) { + Triple wrapped = cardinal.warpTransform(t.getLeftRotation(), t.getScale(), t.getRightRotation()); + delta = target.getRightQuaternion().difference((Quaternionf)wrapped.getRight()).getEulerAnglesXYZ(new Vector3f()); + float l = delta.lengthSquared(); + if (len > l) { + correct = wrapped; + len = l; + } + } + } + + target.setPosition(t.getTranslation()); + target.setLeftQuaternion((Quaternionf)correct.getLeft()); + target.setScale((Vector3f)correct.getMiddle()); + target.setRightQuaternion((Quaternionf)correct.getRight()); + } + + private void recomposeTransform() { + this.transformMatrix + .identity() + .translate(this.globalTransform.getPosition()) + .rotate(this.globalTransform.getLeftQuaternion()) + .scale(this.globalTransform.getScale()) + .rotate(this.globalTransform.getRightQuaternion()); + } + + @Override + public ItemStack getModel() { + return this.itemModels.getFirst(); + } + + @Override + public BoneItems getModels() { + return this.itemModels; + } + + @Override + public void setModel(BlueprintBone bone) { + this.itemModels.update(bone, this.getColor()); + } + + @Override + public void setModel(ItemStack stack) { + if (!this.itemModels.isEqual(Set.of(stack))) { + this.itemModels.clear(); + this.itemModels.add(stack); + } + } + + @Override + public void clearModel() { + this.itemModels.clear(); + } + + @Override + public DataTracker getModelTracker() { + return this.itemModels.getTracker(); + } + + @Override + public Color getDefaultTint() { + return this.defaultTint == null ? this.activeModel.getDefaultTint() : this.defaultTint; + } + + @Override + public Color getDamageTint() { + return this.damageTint == null ? this.activeModel.getDamageTint() : this.damageTint; + } + + @Override + public void setEnchanted(boolean flag) { + if (this.isEnchanted() != flag) { + this.enchanted = flag; + this.itemModels.forEach(itemStack -> { + if (flag) { + itemStack.addUnsafeEnchantment(Enchantment.VANISHING_CURSE, 1); + } else { + itemStack.removeEnchantment(Enchantment.VANISHING_CURSE); + } + }, true); + } + } + + @Override + public boolean isGlowing() { + return this.glowing == null ? this.activeModel.isGlowing() : this.glowing; + } + + @Override + public void setGlowing(@Nullable Boolean flag) { + this.glowing = flag; + this.getData().markBoneGlowing(this, this.glowing != null && this.glowing); + } + + @Override + public int getGlowColor() { + return this.glowColor == null ? this.activeModel.getGlowColor() : this.glowColor; + } + + @Override + public Set getGlowAudience() { + return this.glowing == null ? this.activeModel.getGlowAudience() : this.glowAudience; + } + + @Override + public int getBlockLight() { + return this.blockLight == -1 ? this.activeModel.getBlockLight() : this.blockLight; + } + + @Override + public int getSkyLight() { + return this.skyLight == -1 ? this.activeModel.getSkyLight() : this.skyLight; + } + + @Override + public Billboard getBillboard() { + return this.billboard == null ? this.activeModel.getBillboard() : this.billboard; + } + + @Override + public boolean isVisible() { + return this.visible && !this.scaleHidden; + } + + @Override + public boolean isEffectivelyInvisible() { + return !this.isRenderer + || !this.activeModel.isInvisUpdate() + && (this.scaleHidden || this.modelScale.get().lengthSquared() < 1.0E-5F || this.globalTransform.getScale().lengthSquared() < 1.0E-5F); + } + + @Override + public boolean shouldStep() { + return this.trackedStepFlags.isDirty(); + } + + @Override + public void markStep(StepFlag flag, String animation, float key) { + this.stepFlags.put(animation + ":" + key, flag); + if (flag == StepFlag.SCALE) { + this.scaleStepped = true; + } + } + + @Override + public int getSubTickSamples() { + ModelBoneImpl.SubTicks buffer = this.subTicks; + return buffer == null ? 0 : buffer.samples; + } + + @Override + public void setSubTickSamples(int samples) { + samples = Math.max(0, samples); + if (samples > 0 && this.parent != null && this.parent.getSubTickSamples() < samples) { + this.parent.setSubTickSamples(samples); + } + + if (samples != this.getSubTickSamples()) { + this.subTicks = samples == 0 ? null : new ModelBoneImpl.SubTicks(samples); + } + } + + @Nullable + @Override + public Transform getSubTickTransform(int index) { + ModelBoneImpl.SubTicks buffer = this.subTicks; + return buffer != null && buffer.filled && index >= 0 && index <= buffer.samples ? buffer.transforms[index] : null; + } + + @Nullable + @Override + public Matrix4f getSubTickMatrix(int index) { + ModelBoneImpl.SubTicks buffer = this.subTicks; + return buffer != null && buffer.filled && index >= 0 && index <= buffer.samples ? buffer.matrices[index] : null; + } + + @Nullable + @Override + public Location getSubTickLocation(int index) { + Transform transform = this.getSubTickTransform(index); + return transform == null ? null : this.getLocation(transform.getPosition()); + } + + @Nullable + @Override + public Location getSubTickLocation(int index, OffsetMode mode, Vector3f offset, boolean scale) { + Transform transform = this.getSubTickTransform(index); + if (transform == null) { + return null; + } else { + float angle = -this.getYaw() * (float) (Math.PI / 180.0); + Vector3f bonePosition = transform.getPosition(); + Quaternionf boneLeftRotation = transform.getLeftQuaternion(); + Quaternionf boneRightRotation = transform.getRightQuaternion(); + Quaternionf boneRotation = boneLeftRotation.mul(boneRightRotation, new Quaternionf()); + Vector3f localOffset = new Vector3f(offset); + if (scale) { + localOffset.mul(this.activeModel.getScale()); + } + bonePosition = switch (mode) { + case LOCAL -> bonePosition.add(localOffset.mul(-1.0F, 1.0F, -1.0F).rotate(boneRotation)).rotateY(angle); + case MODEL -> bonePosition.add(localOffset.mul(-1.0F, 1.0F, -1.0F)).rotateY(angle); + case GLOBAL -> bonePosition.rotateY(angle).add(localOffset); + }; + Location pivot = this.isPivotOverride() ? this.getPivotLocation() : this.calculatePivotLocation(); + return pivot.clone().add(bonePosition.x, bonePosition.y, bonePosition.z); + } + } + + @Override + public boolean isSubTickStep(int index) { + ModelBoneImpl.SubTicks buffer = this.subTicks; + return buffer != null && buffer.filled && index >= 0 && index <= buffer.samples ? buffer.steps[index] : false; + } + + private void captureSubTicks() { + ModelBoneImpl.SubTicks buffer = this.subTicks; + if (buffer != null) { + if (this.parent != null) { + int parentSamples = this.parent.getSubTickSamples(); + if (parentSamples > buffer.samples) { + buffer = new ModelBoneImpl.SubTicks(parentSamples); + this.subTicks = buffer; + } else if (parentSamples < buffer.samples) { + this.parent.setSubTickSamples(buffer.samples); + } + } + + int samples = buffer.samples; + buffer.matrices[samples].set(this.transformMatrix); + buffer.transforms[samples].set(this.globalTransform); + boolean hasLast = buffer.hasLastGlobal; + buffer.lastGlobal.set(buffer.tickGlobal); + decomposeInto(this.transformMatrix, buffer.tickGlobal); + buffer.hasLastGlobal = true; + boolean rootBone = this.isRootBone(); + boolean onGround = this.isBoneOnGround; + boolean globalRotation = this.hasGlobalRotation; + boolean stepped = this.scaleStepped; + buffer.tickLocal.set(this.localTransform); + buffer.tickSteps.clear(); + buffer.tickSteps.putAll(this.stepFlags); + buffer.lastSteps.clear(); + boolean sampled = !this.proceduralTransform && this.animationDrivesTransform(buffer); + + for (int i = 0; i < samples; i++) { + double alpha = (double)i / samples; + Matrix4f matrix = buffer.matrices[i]; + Transform transform = buffer.transforms[i]; + if (sampled) { + this.applyAnimationSample(buffer, alpha); + this.composeSubTickMatrix(matrix, i); + decomposeInto(matrix, transform); + buffer.steps[i] = i > 0 && !this.stepFlags.equals(buffer.lastSteps); + buffer.lastSteps.clear(); + buffer.lastSteps.putAll(this.stepFlags); + } else { + interpolateTickGlobal(buffer, transform, hasLast ? (float)alpha : 1.0F); + matrix.set(transform.createMatrix()); + buffer.steps[i] = false; + } + + transform.setScale(transform.getScale().mul((Vector3fc)this.modelScale.get()).mul(this.activeModel.getScale())); + transform.setPosition(rootBone ? new Vector3f() : transform.getPosition().mul(this.activeModel.getScale())); + } + + buffer.steps[samples] = sampled && !buffer.tickSteps.equals(buffer.lastSteps); + this.localTransform.set(buffer.tickLocal); + this.stepFlags.clear(); + this.isBoneOnGround = onGround; + this.hasGlobalRotation = globalRotation; + this.scaleStepped = stepped; + buffer.filled = true; + } + } + + private boolean animationDrivesTransform(ModelBoneImpl.SubTicks buffer) { + this.applyAnimationSample(buffer, 1.0); + this.composeSubTickMatrix(buffer.probe, buffer.samples); + return buffer.probe.equals(this.transformMatrix, 0.001F); + } + + private void applyAnimationSample(ModelBoneImpl.SubTicks buffer, double alpha) { + this.localTransform.identity(); + this.localTransform.setPosition(this.blueprintBone.getLocalPosition()); + this.localTransform.setLeftEuler(this.blueprintBone.getLocalRotation()); + this.stepFlags.clear(); + this.activeModel.getAnimationHandler().updateBone(this, property -> SubTickProperty.at(property, alpha)); + if (this.scaleHidden) { + this.localTransform.setScale(buffer.tickLocal.getScale()); + } + } + + private void composeSubTickMatrix(Matrix4f target, int index) { + target.identity(); + if (this.parent != null) { + Matrix4f parentMatrix = this.parent.getSubTickMatrix(index); + target.set(parentMatrix == null ? this.parent.getTransformMatrix() : parentMatrix); + } + + target.translate(this.localTransform.getPosition()); + if (this.parent != null && this.hasGlobalRotation) { + Transform parentTransform = this.parent.getSubTickTransform(index); + Quaternionf parentLeft = parentTransform == null ? this.parent.getGlobalTransform().getLeftQuaternion() : parentTransform.getLeftQuaternion(); + target.rotate(parentLeft.invert()); + } + + target.rotate(this.localTransform.getLeftQuaternion()); + TMath.clampedScale(target, this.localTransform.getScale()); + target.rotate(this.localTransform.getRightQuaternion()); + } + + private static void interpolateTickGlobal(ModelBoneImpl.SubTicks buffer, Transform target, float alpha) { + target.setPosition(TMath.lerp(buffer.lastGlobal.getPosition(), buffer.tickGlobal.getPosition(), (double)alpha)); + target.setLeftQuaternion(buffer.lastGlobal.getLeftQuaternion().slerp(buffer.tickGlobal.getLeftQuaternion(), alpha)); + target.setScale(TMath.lerp(buffer.lastGlobal.getScale(), buffer.tickGlobal.getScale(), (double)alpha)); + target.setRightQuaternion(buffer.lastGlobal.getRightQuaternion().slerp(buffer.tickGlobal.getRightQuaternion(), alpha)); + } + + @Override + public boolean pollModelScaleChanged() { + if (this.modelScale.isDirty()) { + this.modelScale.clearDirty(); + return true; + } else { + return false; + } + } + + @Override + public boolean isRootBone() { + return this.activeModel.getModeledEntity().getRootMotionHandler().getRootBone() == this; + } + + @Override + public Location getLocationUnsafe() { + return this.getLocation(this.globalTransform.getPosition()); + } + + @Override + public Location getLocation() { + return this.getLocation(this.globalTransform.getSafePosition()); + } + + private Location getLocation(Vector3f bonePosition) { + float angle = -this.getYaw() * (float) (Math.PI / 180.0); + bonePosition = bonePosition.rotateY(angle, new Vector3f()); + Location pivot = this.isPivotOverride() ? this.getPivotLocation() : this.calculatePivotLocation(); + return pivot.clone().add(bonePosition.x, bonePosition.y, bonePosition.z); + } + + @Override + public Location getLocation(OffsetMode mode, Vector3f offset, boolean scale, boolean safe) { + float angle = -this.getYaw() * (float) (Math.PI / 180.0); + Vector3f bonePosition = safe ? this.globalTransform.getSafePosition() : this.globalTransform.getPosition(); + Quaternionf boneLeftRotation = safe ? this.globalTransform.getSafeLeftQuaternion() : this.globalTransform.getLeftQuaternion(); + Quaternionf boneRightRotation = safe ? this.globalTransform.getSafeRightQuaternion() : this.globalTransform.getRightQuaternion(); + Quaternionf boneRotation = boneLeftRotation.mul(boneRightRotation, new Quaternionf()); + if (scale) { + offset.mul(this.activeModel.getScale()); + } + bonePosition = switch (mode) { + case LOCAL -> bonePosition.add(offset.mul(-1.0F, 1.0F, -1.0F).rotate(boneRotation)).rotateY(angle); + case MODEL -> bonePosition.add(offset.mul(-1.0F, 1.0F, -1.0F)).rotateY(angle); + case GLOBAL -> bonePosition.rotateY(angle).add(offset); + }; + Location pivot = this.isPivotOverride() ? this.getPivotLocation() : this.calculatePivotLocation(); + return pivot.clone().add(bonePosition.x, bonePosition.y, bonePosition.z); + } + + @Override + public void addBoneBehavior(BoneBehavior boneBehavior) { + this.boneBehaviors.put(boneBehavior.getType(), boneBehavior); + this.boneBehaviorsArray = this.boneBehaviors.values().toArray(new BoneBehavior[0]); + boneBehavior.onApply(); + this.proceduralTypes.addAll(boneBehavior.getType().getProceduralTypes()); + this.proceduralAnimation = this.proceduralTypes.contains(ProceduralType.ANIMATION); + this.proceduralTransform = this.proceduralTypes.contains(ProceduralType.TRANSFORM); + this.pivotOverride = this.pivotOverride | boneBehavior.getType().isPivot(); + } + + @Override + public boolean hasBoneBehavior(BoneBehaviorType type) { + for (BoneBehavior behavior : this.boneBehaviorsArray) { + if (behavior.getType() == type) { + return true; + } + } + + return false; + } + + @Override + public Optional getBoneBehavior(BoneBehaviorType type) { + BoneBehavior behavior = null; + + for (BoneBehavior b : this.boneBehaviorsArray) { + if (b.getType() == type) { + behavior = b; + break; + } + } + + return Optional.ofNullable((T)behavior); + } + + @Override + public Optional removeBoneBehavior(BoneBehaviorType type) { + BoneBehavior behavior = this.boneBehaviors.remove(type); + if (behavior != null) { + this.boneBehaviorsArray = this.boneBehaviors.values().toArray(new BoneBehavior[0]); + behavior.onRemove(); + this.proceduralTypes.clear(); + + for (BoneBehavior b : this.boneBehaviorsArray) { + this.proceduralTypes.addAll(b.getType().getProceduralTypes()); + } + + this.proceduralAnimation = this.proceduralTypes.contains(ProceduralType.ANIMATION); + this.proceduralTransform = this.proceduralTypes.contains(ProceduralType.TRANSFORM); + } + + return Optional.ofNullable((T)behavior); + } + + @Override + public Map, BoneBehavior> getImmutableBoneBehaviors() { + return ImmutableMap.copyOf(this.boneBehaviors); + } + + @Override + public boolean hasBoneBehaviors() { + return this.boneBehaviorsArray.length > 0; + } + + @Override + public void forBehaviors(Consumer consumer) { + for (BoneBehavior behavior : this.boneBehaviorsArray) { + consumer.accept(behavior); + } + } + + private void tryTintModel() { + Color color = this.getColor(); + if (color != this.lastColor) { + this.lastColor = color; + this.itemModels.forEachMutating(itemStack -> ModelEngineAPI.getNMSHandler().colorStack(itemStack, color)); + } + } + + private Color getColor() { + return this.activeModel.isMarkedHurt() ? this.getDamageTint() : this.getDefaultTint(); + } + + @Override + public void save(SavedData data) { + if (this.defaultTint != null) { + data.putInt("default_tint", this.defaultTint.asRGB()); + } + + if (this.damageTint != null) { + data.putInt("damage_tint", this.damageTint.asRGB()); + } + + if (this.blueprintBone.isRenderByDefault() != this.visible) { + data.putBoolean("visible", this.visible); + } + + if (this.isEnchanted()) { + data.putBoolean("enchant", true); + } + + if (this.glowing != null) { + data.putBoolean("glowing", this.glowing); + } + + if (this.glowColor != null) { + data.putInt("glow_color", this.glowColor); + } + + if (this.blockLight > 0) { + data.putInt("block_light", this.blockLight); + } + + if (this.skyLight > 0) { + data.putInt("sky_light", this.skyLight); + } + + if (!this.tickDependencies.isEmpty()) { + data.putList("tick_dependencies", this.tickDependencies); + } + + this.forBehaviors(behavior -> behavior.save().ifPresent(data1 -> data.putData(behavior.getType().getId(), data1))); + } + + @Override + public void load(SavedData data) { + Integer defaultTint = data.getInt("default_tint"); + if (defaultTint != null) { + this.setDefaultTint(Color.fromRGB(defaultTint)); + } + + Integer damageTint = data.getInt("damage_tint"); + if (damageTint != null) { + this.setDamageTint(Color.fromRGB(damageTint)); + } + + Boolean visible = data.getBoolean("visible"); + if (visible != null) { + this.setVisible(visible); + } + + if (data.getBoolean("enchant", false)) { + this.setEnchanted(true); + } + + this.setGlowing(data.getBoolean("glowing")); + this.setGlowColor(data.getInt("glow_color")); + this.setBlockLight(data.getInt("block_light", -1)); + this.setSkyLight(data.getInt("sky_light", -1)); + List tickDep = data.getList("tick_dependencies", String.class); + if (tickDep != null) { + this.tickDependencies.addAll(tickDep); + } + + this.forBehaviors(behavior -> data.getData(behavior.getType().getId()).ifPresent(behavior::load)); + } + + private IEntityData getData() { + return this.activeModel.getModeledEntity().getBase().getData(); + } + + private void queueVelocity(RootMotion rootMotion) { + this.activeModel.getModeledEntity().getRootMotionHandler().queueVelocity(rootMotion); + } + + @NotNull + @Override + public ActiveModel getActiveModel() { + return this.activeModel; + } + + @NotNull + @Override + public BlueprintBone getBlueprintBone() { + return this.blueprintBone; + } + + @Override + public Map getChildren() { + return this.children; + } + + public BoneBehavior[] getBoneBehaviorsArray() { + return this.boneBehaviorsArray; + } + + public BoneItems getItemModels() { + return this.itemModels; + } + + public DataTracker getModelScale() { + return this.modelScale; + } + + public Set getProceduralTypes() { + return this.proceduralTypes; + } + + public boolean isProceduralAnimation() { + return this.proceduralAnimation; + } + + public boolean isProceduralTransform() { + return this.proceduralTransform; + } + + @Override + public ManualAnimator getManualAnimator() { + return this.manualAnimator; + } + + @Override + public SafeTransform getLocalTransform() { + return this.localTransform; + } + + @Override + public SafeTransform getGlobalTransform() { + return this.globalTransform; + } + + @Override + public Matrix4f getTransformMatrix() { + return this.transformMatrix; + } + + public Map getStepFlags() { + return this.stepFlags; + } + + public DataTracker> getTrackedStepFlags() { + return this.trackedStepFlags; + } + + @Override + public Set getTickDependencies() { + return this.tickDependencies; + } + + @Override + public String getCustomId() { + return this.customId; + } + + @Nullable + @Override + public ModelBone getParent() { + return this.parent; + } + + @Nullable + @Override + public ModelBone getPivot() { + return this.pivot; + } + + @Override + public boolean isPivotOverride() { + return this.pivotOverride; + } + + @Override + public Location getPivotLocation() { + return this.pivotLocation; + } + + @Override + public boolean isRenderer() { + return this.isRenderer; + } + + @Override + public float getYaw() { + return this.yaw; + } + + public boolean isHasGlobalRotation() { + return this.hasGlobalRotation; + } + + public Color getLastColor() { + return this.lastColor; + } + + @Override + public boolean isEnchanted() { + return this.enchanted; + } + + @Override + public boolean isScaleHidden() { + return this.scaleHidden; + } + + public boolean isScaleStepped() { + return this.scaleStepped; + } + + @Override + public boolean isMarkedDestroy() { + return this.markedDestroy; + } + + public boolean isBoneOnGround() { + return this.isBoneOnGround; + } + + @Override + public void setManualAnimator(ManualAnimator manualAnimator) { + this.manualAnimator = manualAnimator; + } + + @Override + public void setCustomId(String customId) { + this.customId = customId; + } + + @Override + public void setPivot(@Nullable ModelBone pivot) { + this.pivot = pivot; + } + + @Override + public void setPivotLocation(Location pivotLocation) { + this.pivotLocation = pivotLocation; + } + + @Override + public void setRenderer(boolean isRenderer) { + this.isRenderer = isRenderer; + } + + @Override + public void setYaw(float yaw) { + this.yaw = yaw; + } + + @Override + public void setHasGlobalRotation(boolean hasGlobalRotation) { + this.hasGlobalRotation = hasGlobalRotation; + } + + @Override + public void setDefaultTint(Color defaultTint) { + this.defaultTint = defaultTint; + } + + @Override + public void setDamageTint(Color damageTint) { + this.damageTint = damageTint; + } + + @Override + public void setGlowColor(Integer glowColor) { + this.glowColor = glowColor; + } + + @Override + public void setGlowAudience(Set glowAudience) { + this.glowAudience = glowAudience; + } + + @Override + public void setBlockLight(int blockLight) { + this.blockLight = blockLight; + } + + @Override + public void setSkyLight(int skyLight) { + this.skyLight = skyLight; + } + + @Override + public void setBillboard(Billboard billboard) { + this.billboard = billboard; + } + + @Override + public void setVisible(boolean visible) { + this.visible = visible; + } + + public void setMarkedDestroy(boolean markedDestroy) { + this.markedDestroy = markedDestroy; + } + + @Override + public void setBoneOnGround(boolean isBoneOnGround) { + this.isBoneOnGround = isBoneOnGround; + } + + private static class SubTicks { + private final int samples; + private final Matrix4f[] matrices; + private final Transform[] transforms; + private final boolean[] steps; + private final Matrix4f probe = new Matrix4f(); + private final Transform tickLocal = new Transform(); + private final Transform tickGlobal = new Transform(); + private final Transform lastGlobal = new Transform(); + private boolean hasLastGlobal; + private volatile boolean filled; + private final Map tickSteps = new HashMap<>(); + private final Map lastSteps = new HashMap<>(); + + private SubTicks(int samples) { + this.samples = samples; + this.matrices = new Matrix4f[samples + 1]; + this.transforms = new Transform[samples + 1]; + this.steps = new boolean[samples + 1]; + + for (int i = 0; i <= samples; i++) { + this.matrices[i] = new Matrix4f(); + this.transforms[i] = new Transform(); + } + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/AbstractSegmentImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/AbstractSegmentImpl.java new file mode 100644 index 0000000..217cc59 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/AbstractSegmentImpl.java @@ -0,0 +1,354 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.type.Segment; +import com.ticxo.modelengine.api.utils.math.TMath; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; +import org.joml.AxisAngle4f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class AbstractSegmentImpl extends AbstractBoneBehavior implements Segment { + protected final boolean backPivot; + protected boolean bounded; + protected float minX; + protected float maxX; + protected float minY; + protected float maxY; + protected float minZ; + protected float maxZ; + protected float alignRate; + protected float elasticity; + protected final Vector3f delta = new Vector3f(); + protected final Vector3f deltaNorm = new Vector3f(); + protected final Vector3f worldLocation = new Vector3f(); + protected UUID scaleCallback; + protected float boneLength; + protected float modelScale = 1.0F; + + public AbstractSegmentImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + this.backPivot = data.get("back_pivot", true); + this.bounded = data.get("bounded", true); + this.minX = data.get("min_x", -50.0F); + this.maxX = data.get("max_x", 50.0F); + this.minY = data.get("min_y", -50.0F); + this.maxY = data.get("max_y", 50.0F); + this.minZ = data.get("min_z", -50.0F); + this.maxZ = data.get("max_z", 50.0F); + this.alignRate = data.get("align_rate", 0.25F); + this.elasticity = data.get("elasticity", 0.0F); + } + + @Override + public void onApply() { + if (this.backPivot) { + this.delta.set(this.bone.getBlueprintBone().getLocalPosition()); + this.delta.normalize(this.deltaNorm); + this.boneLength = this.delta.length(); + Vector3fc scale = this.bone.getActiveModel().getScale(); + this.modelScale = scale.get(scale.maxComponent()); + this.scaleCallback = this.bone.getActiveModel().getScaleCallback().subscribe((model, s) -> this.modelScale = (float)s); + this.worldLocation.set(this.bone.getLocation().toVector().toVector3f()); + } + } + + @Override + public void onModelInitialized() { + if (!this.backPivot) { + Optional maybeControlBone = this.getControlBone(); + if (maybeControlBone.isEmpty()) { + throw new RuntimeException("Missing control bone for: " + this.bone.getBoneId()); + } else { + ModelBone controlBone = maybeControlBone.get(); + this.delta.set(controlBone.getBlueprintBone().getLocalPosition()); + this.delta.normalize(this.deltaNorm); + this.boneLength = this.delta.length(); + Vector3fc scale = this.bone.getActiveModel().getScale(); + this.modelScale = scale.get(scale.maxComponent()); + this.scaleCallback = this.bone.getActiveModel().getScaleCallback().subscribe((model, s) -> this.modelScale = (float)s); + this.worldLocation.set(controlBone.getLocation().toVector().toVector3f()); + } + } + } + + private Optional getControlBone() { + Map children = this.bone.getChildren(); + if (children.isEmpty()) { + return Optional.empty(); + } else { + return children.size() == 1 ? children.values().stream().findFirst() : Optional.ofNullable(children.get(this.bone.getBoneId() + "_ctrl")); + } + } + + @Override + public void onRemove() { + this.bone.getActiveModel().getScaleCallback().unsubscribe(this.scaleCallback); + } + + @Override + public void postGlobalCalculation() { + if (this.modelScale != 0.0F) { + if (this.backPivot) { + this.backPivotCalculation(); + } else { + this.frontPivotCalculation(); + } + } + } + + private void frontPivotCalculation() { + Matrix4f parentTransform = this.getParent(parent -> new Matrix4f(parent.getTransformMatrix()), new Matrix4f()); + if (parentTransform.determinant() != 0.0F) { + parentTransform.translate(this.bone.getLocalTransform().getPosition()).rotate(this.bone.getBlueprintBone().getLocalQuaternion()); + Matrix4f invParentTransform = parentTransform.invert(new Matrix4f()); + Vector3f pivotLocation = this.bone.calculatePivotLocation().toVector().toVector3f(); + Vector3f parentLocation = TMath.transform(this.bone.getTransformMatrix(), new Vector3f()) + .rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0)) + .mul(this.modelScale) + .add(pivotLocation); + Matrix4f transformMatrix = this.bone.getTransformMatrix(); + Vector3f originPosition = TMath.transform(transformMatrix, this.delta) + .rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0)) + .mul(this.modelScale) + .add(pivotLocation); + float animatedBoneLength = originPosition.distance(parentLocation); + float finalBoneLength = TMath.lerp(this.boneLength * this.modelScale, animatedBoneLength, this.elasticity); + this.worldLocation.lerp(originPosition, this.alignRate).sub(parentLocation); + if (this.worldLocation.lengthSquared() > 1.0E-6F) { + this.worldLocation.normalize(finalBoneLength); + } + + this.worldLocation.add(parentLocation); + Vector3f globalPosition = this.worldLocation + .sub(pivotLocation, new Vector3f()) + .mul(1.0F / this.modelScale) + .rotateY(this.bone.getYaw() * (float) (Math.PI / 180.0)); + Vector3f localPosition = TMath.transform(invParentTransform, globalPosition); + Quaternionf q = new Quaternionf(); + if (this.bounded) { + Vector3f normLocalPosition = localPosition.normalize(new Vector3f()); + Vector3f axis = this.deltaNorm.cross(normLocalPosition, new Vector3f()).normalize(); + float angle = (float)Math.acos(this.deltaNorm.dot(normLocalPosition)); + q.set(new AxisAngle4f(angle, axis)); + if (!q.isFinite()) { + this.deltaNorm.rotationTo(localPosition, q); + } else { + Vector3f euler = TMath.toEulerZYX(q, new Vector3f()); + euler.x = TMath.clamp(euler.x, this.minX, this.maxX) * (float) (Math.PI / 180.0); + euler.y = TMath.clamp(euler.y, this.minY, this.maxY) * (float) (Math.PI / 180.0); + euler.z = TMath.clamp(euler.z, this.minZ, this.maxZ) * (float) (Math.PI / 180.0); + TMath.toQuaternion(euler, q); + this.deltaNorm.rotate(q, localPosition).mul(finalBoneLength / this.modelScale); + } + } else { + this.deltaNorm.rotationTo(localPosition, q); + } + + transformMatrix.set(parentTransform); + this.worldLocation + .set(TMath.transform(transformMatrix, localPosition)) + .rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0)) + .mul(this.modelScale) + .add(pivotLocation); + transformMatrix.rotate(q); + } + } + + private void backPivotCalculation() { + Matrix4f parentTransform = this.getParent(ModelBone::getTransformMatrix, new Matrix4f()); + Matrix4f invParentTransform = parentTransform.invert(new Matrix4f()); + Vector3f pivotLocation = this.bone.calculatePivotLocation().toVector().toVector3f(); + Vector3f parentLocation = this.getParent(parent -> parent.getLocationUnsafe().toVector().toVector3f(), pivotLocation); + Matrix4f transformMatrix = this.bone.getTransformMatrix(); + Vector3f originPosition = TMath.transform(transformMatrix, new Vector3f()) + .rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0)) + .mul(this.modelScale) + .add(pivotLocation); + float animatedBoneLength = originPosition.distance(parentLocation); + float finalBoneLength = TMath.lerp(this.boneLength * this.modelScale, animatedBoneLength, this.elasticity); + this.worldLocation.lerp(originPosition, this.alignRate).sub(parentLocation); + if (this.worldLocation.lengthSquared() > 1.0E-6F) { + this.worldLocation.normalize(finalBoneLength); + } + + this.worldLocation.add(parentLocation); + Vector3f globalPosition = this.worldLocation + .sub(pivotLocation, new Vector3f()) + .mul(1.0F / this.modelScale) + .rotateY(this.bone.getYaw() * (float) (Math.PI / 180.0)); + Vector3f localPosition = TMath.transform(invParentTransform, globalPosition); + Quaternionf q = new Quaternionf(); + if (this.bounded) { + Vector3f normLocalPosition = localPosition.normalize(new Vector3f()); + Vector3f axis = this.deltaNorm.cross(normLocalPosition, new Vector3f()).normalize(); + float angle = (float)Math.acos(this.deltaNorm.dot(normLocalPosition)); + q.set(new AxisAngle4f(angle, axis)); + if (!q.isFinite()) { + this.deltaNorm.rotationTo(localPosition, q); + } else { + Vector3f euler = TMath.toEulerZYX(q, new Vector3f()); + euler.x = TMath.clamp(euler.x, this.minX, this.maxX) * (float) (Math.PI / 180.0); + euler.y = TMath.clamp(euler.y, this.minY, this.maxY) * (float) (Math.PI / 180.0); + euler.z = TMath.clamp(euler.z, this.minZ, this.maxZ) * (float) (Math.PI / 180.0); + TMath.toQuaternion(euler, q); + this.deltaNorm.rotate(q, localPosition).mul(finalBoneLength / this.modelScale); + } + } else { + this.deltaNorm.rotationTo(localPosition, q); + } + + transformMatrix.set(parentTransform).translate(localPosition); + this.worldLocation + .set(TMath.transform(transformMatrix, new Vector3f())) + .rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0)) + .mul(this.modelScale) + .add(pivotLocation); + transformMatrix.rotate(q).rotate(this.bone.getBlueprintBone().getLocalQuaternion()); + } + + private R getParent(Function function, R def) { + return this.bone.getParent() == null ? def : function.apply(this.bone.getParent()); + } + + public boolean isBackPivot() { + return this.backPivot; + } + + @Override + public boolean isBounded() { + return this.bounded; + } + + @Override + public float getMinX() { + return this.minX; + } + + @Override + public float getMaxX() { + return this.maxX; + } + + @Override + public float getMinY() { + return this.minY; + } + + @Override + public float getMaxY() { + return this.maxY; + } + + @Override + public float getMinZ() { + return this.minZ; + } + + @Override + public float getMaxZ() { + return this.maxZ; + } + + @Override + public float getAlignRate() { + return this.alignRate; + } + + @Override + public float getElasticity() { + return this.elasticity; + } + + @Override + public Vector3f getDelta() { + return this.delta; + } + + public Vector3f getDeltaNorm() { + return this.deltaNorm; + } + + @Override + public Vector3f getWorldLocation() { + return this.worldLocation; + } + + public UUID getScaleCallback() { + return this.scaleCallback; + } + + public float getBoneLength() { + return this.boneLength; + } + + public float getModelScale() { + return this.modelScale; + } + + @Override + public void setBounded(boolean bounded) { + this.bounded = bounded; + } + + @Override + public void setMinX(float minX) { + this.minX = minX; + } + + @Override + public void setMaxX(float maxX) { + this.maxX = maxX; + } + + @Override + public void setMinY(float minY) { + this.minY = minY; + } + + @Override + public void setMaxY(float maxY) { + this.maxY = maxY; + } + + @Override + public void setMinZ(float minZ) { + this.minZ = minZ; + } + + @Override + public void setMaxZ(float maxZ) { + this.maxZ = maxZ; + } + + @Override + public void setAlignRate(float alignRate) { + this.alignRate = alignRate; + } + + @Override + public void setElasticity(float elasticity) { + this.elasticity = elasticity; + } + + public void setScaleCallback(UUID scaleCallback) { + this.scaleCallback = scaleCallback; + } + + public void setBoneLength(float boneLength) { + this.boneLength = boneLength; + } + + public void setModelScale(float modelScale) { + this.modelScale = modelScale; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/Dummy.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/Dummy.java new file mode 100644 index 0000000..ce9eacb --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/Dummy.java @@ -0,0 +1,12 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; + +public class Dummy extends AbstractBoneBehavior { + public Dummy(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/GhostImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/GhostImpl.java new file mode 100644 index 0000000..2926196 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/GhostImpl.java @@ -0,0 +1,25 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.ticxo.modelengine.api.model.bone.BoneItems; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.type.Ghost; + +public class GhostImpl extends AbstractBoneBehavior implements Ghost { + public GhostImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + } + + @Override + public void onApply() { + this.bone.setRenderer(true); + this.bone.clearModel(); + } + + @Override + public BoneItems getModel() { + return this.bone.getModels(); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeadForcedImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeadForcedImpl.java new file mode 100644 index 0000000..403d8b3 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeadForcedImpl.java @@ -0,0 +1,71 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.utils.math.TMath; +import java.util.Optional; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; + +public class HeadForcedImpl extends HeadImpl { + protected boolean inherited; + + public HeadForcedImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + this.onParentSwap(bone.getParent()); + } + + @Override + public void onParentSwap(@Nullable ModelBone parent) { + this.shouldRotate = false; + if (parent != null) { + Optional maybeBehavior = parent.getBoneBehavior(this.type); + maybeBehavior.ifPresent(head -> { + this.inherited = head.inherited; + if (!this.inherited && !(head instanceof HeadForcedImpl)) { + this.shouldRotate = true; + this.local = head.isLocal(); + } + }); + } + } + + @Override + public void preGlobalRotate() { + if (this.shouldRotate && !this.local) { + this.rotate(); + } + } + + @Override + public void postGlobalRotate() { + if (this.shouldRotate && this.local) { + this.rotate(); + } + } + + private void rotate() { + ActiveModel activeModel = this.bone.getActiveModel(); + float yaw = -TMath.degreeDifference(activeModel.getYBodyRot(), activeModel.getYHeadRot()); + float pitch = -activeModel.getXHeadRot(); + Quaternionf q = new Quaternionf().rotateX(pitch * (float) (Math.PI / 180.0)).rotateY(-yaw * (float) (Math.PI / 180.0)); + this.bone.getTransformMatrix().rotate(q); + } + + @Override + public boolean isHidden() { + return true; + } + + @Override + public boolean isInherited() { + return this.inherited; + } + + @Override + public void setInherited(boolean inherited) { + this.inherited = inherited; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeadImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeadImpl.java new file mode 100644 index 0000000..f6f16e2 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeadImpl.java @@ -0,0 +1,88 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.type.Head; +import com.ticxo.modelengine.api.utils.math.TMath; +import java.util.Optional; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HeadImpl extends AbstractBoneBehavior implements Head { + protected boolean shouldRotate; + protected boolean inherited; + protected boolean local; + private final Vector3f pivot = new Vector3f(); + + public HeadImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + this.onParentSwap(bone.getParent()); + this.local = data.get("local", false); + this.inherited = data.get("inherited", false); + } + + @Override + public void onParentSwap(@Nullable ModelBone parent) { + this.shouldRotate = true; + + while (parent != null) { + Optional maybeBehavior = parent.getBoneBehavior(this.type); + this.shouldRotate = maybeBehavior.isEmpty() || maybeBehavior.get() instanceof HeadForcedImpl; + if (!this.shouldRotate) { + return; + } + + parent = parent.getParent(); + } + } + + @Override + public void postGlobalTranslate() { + this.bone.getTransformMatrix().getTranslation(this.pivot); + } + + @Override + public void postTransformDecompose() { + if (this.shouldRotate && !this.local) { + Quaternionf rotation = this.getRotation(); + this.bone.getGlobalTransform().mutatePosition(vector3f -> vector3f.sub(this.pivot).rotate(rotation).add(this.pivot)); + this.bone.getGlobalTransform().mutateLeftQuaternion(quaternionf -> quaternionf.premul(rotation)); + } + } + + @Override + public void postGlobalRotate() { + if (this.shouldRotate && this.local) { + this.bone.getTransformMatrix().rotate(this.getRotation()); + } + } + + private Quaternionf getRotation() { + ActiveModel activeModel = this.bone.getActiveModel(); + float yaw = TMath.degreeDifference(activeModel.getYBodyRot(), activeModel.getYHeadRot()); + float pitch = activeModel.getXHeadRot(); + return new Quaternionf().rotateY(-yaw * (float) (Math.PI / 180.0)).rotateX(pitch * (float) (Math.PI / 180.0)); + } + + public boolean isInherited() { + return this.inherited; + } + + public void setInherited(boolean inherited) { + this.inherited = inherited; + } + + @Override + public boolean isLocal() { + return this.local; + } + + @Override + public void setLocal(boolean local) { + this.local = local; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeldItemImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeldItemImpl.java new file mode 100644 index 0000000..3d57497 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/HeldItemImpl.java @@ -0,0 +1,114 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.type.HeldItem; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import java.util.function.Supplier; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.bukkit.inventory.ItemStack; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HeldItemImpl extends AbstractBoneBehavior implements HeldItem { + private final Vector3f location = new Vector3f(); + private final Quaternionf rotation = new Quaternionf(); + private ItemDisplayTransform display; + private HeldItem.ItemStackSupplier itemProvider; + + public HeldItemImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + this.display = data.get("display"); + } + + @Override + public void onApply() { + if (this.bone.getActiveModel().getModelRenderer() instanceof DisplayRenderer) { + this.bone.setRenderer(true); + this.bone.setModel(EMPTY); + } + } + + @Override + public void onFinalize() { + float yaw = -this.bone.getYaw() * (float) (Math.PI / 180.0); + this.bone.getGlobalTransform().mutatePosition(pos -> pos.rotateY(yaw, this.location)); + this.bone.getGlobalTransform().mutateLeftQuaternion(q -> q.premul(this.rotation.rotationZYX(0.0F, yaw, 0.0F), this.rotation)); + if (this.itemProvider == null) { + this.bone.setModel(EMPTY); + } else { + this.bone.setModel(this.itemProvider.supply()); + } + } + + @Override + public void save(SavedData data) { + if (this.itemProvider != null) { + this.itemProvider.save().ifPresent(data1 -> data.putData("supplier", data1)); + } + } + + @Override + public void load(SavedData data) { + data.getData("supplier").ifPresent(data1 -> { + String var2 = data1.getString("type", ""); + + this.itemProvider = (HeldItem.ItemStackSupplier)(switch (var2) { + case "static" -> new HeldItem.StaticItemStackSupplier(); + case "equipment" -> new HeldItem.EquipmentSupplier(); + default -> null; + }); + if (this.itemProvider != null) { + this.itemProvider.load(data1); + } + }); + } + + @Override + public void clearItemProvider() { + this.itemProvider = null; + } + + @Override + public void setItemProvider(Supplier stackSupplier) { + this.setItemProvider(new HeldItem.TemporaryItemStackSupplier(stackSupplier)); + } + + @Override + public void setItemProvider(HeldItem.ItemStackSupplier stackSupplier) { + this.itemProvider = stackSupplier; + } + + @Override + public ItemStack getItem() { + return this.bone.getModel(); + } + + @Override + public Vector3f getLocation() { + return this.location; + } + + @Override + public Quaternionf getRotation() { + return this.rotation; + } + + @Override + public ItemDisplayTransform getDisplay() { + return this.display; + } + + @Override + public void setDisplay(ItemDisplayTransform display) { + this.display = display; + } + + @Override + public HeldItem.ItemStackSupplier getItemProvider() { + return this.itemProvider; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/LeashImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/LeashImpl.java new file mode 100644 index 0000000..d9b8934 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/LeashImpl.java @@ -0,0 +1,92 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.LeashManager; +import com.ticxo.modelengine.api.model.bone.type.Leash; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.joml.Vector3f; + +public class LeashImpl extends AbstractBoneBehavior implements Leash { + private final boolean mainLeash; + private final int id; + private final Vector3f location = new Vector3f(); + private Entity connectedEntity; + private Leash connectedLeash; + + public LeashImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + this.mainLeash = data.get("main", false); + this.id = ModelEngineAPI.getEntityHandler().getNextEntityId(); + } + + @Override + public void onApply() { + this.bone.getActiveModel().getLeashManager().ifPresent(leashManager -> ((LeashManager)leashManager).registerLeash(this)); + Location baseLocation = this.bone.calculatePivotLocation(); + this.bone + .getBlueprintBone() + .getLocalPosition() + .rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location) + .add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ()); + } + + @Override + public void onFinalize() { + Location baseLocation = this.bone.calculatePivotLocation(); + this.bone + .getGlobalTransform() + .mutatePosition( + vector3f -> vector3f.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location) + .add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ()) + ); + } + + @Override + public void connect(Entity entity) { + this.connectedEntity = entity; + } + + @Override + public void connect(T leash) { + if (leash != this) { + this.connectedLeash = leash; + } + } + + @Override + public void disconnect() { + this.connectedEntity = null; + this.connectedLeash = null; + } + + @Override + public T getConnectedLeash() { + return (T)this.connectedLeash; + } + + @Override + public boolean isMainLeash() { + return this.mainLeash; + } + + @Override + public int getId() { + return this.id; + } + + @Override + public Vector3f getLocation() { + return this.location; + } + + @Override + public Entity getConnectedEntity() { + return this.connectedEntity; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/MountImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/MountImpl.java new file mode 100644 index 0000000..11c1e5a --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/MountImpl.java @@ -0,0 +1,142 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.joml.Vector3f; + +public class MountImpl extends AbstractBoneBehavior implements Mount { + private final boolean driver; + private final Vector3f location = new Vector3f(); + private final Vector3f globalLocation = new Vector3f(); + private final Set passengers = Sets.newConcurrentHashSet(); + private final Map entityIdCache = new ConcurrentHashMap<>(); + + public MountImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + this.driver = data.get("driver", false); + } + + @Override + public void onApply() { + this.bone.getActiveModel().getMountManager().ifPresent(mountManager -> { + if (this.driver) { + ((MountManager)mountManager).setDriverBone(this); + } else { + ((MountManager)mountManager).registerSeat(this); + } + }); + this.bone.getBlueprintBone().getLocalPosition().rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location); + Location baseLocation = this.bone.calculatePivotLocation(); + this.globalLocation.set(this.location).add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ()); + } + + @Override + public void onFinalize() { + this.bone.getGlobalTransform().mutatePosition(pos -> pos.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location)); + Location baseLocation = this.bone.calculatePivotLocation(); + this.globalLocation.set(this.location).add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ()); + this.passengers.removeIf(entity -> ModelEngineAPI.getEntityHandler().isRemoved(entity)); + } + + @Override + public boolean addPassenger(Entity entity) { + if (this.canMountMore()) { + this.passengers.add(entity); + if (ServerInfo.IS_FOLIA) { + this.entityIdCache.put(entity, entity.getEntityId()); + } + + return true; + } else { + return false; + } + } + + @Override + public boolean addPassengers(Collection entities) { + for (Entity entity : entities) { + if (!this.canMountMore()) { + return false; + } + + this.passengers.add(entity); + if (ServerInfo.IS_FOLIA) { + this.entityIdCache.put(entity, entity.getEntityId()); + } + } + + return true; + } + + @Override + public void removePassenger(Entity entity) { + this.passengers.remove(entity); + if (ServerInfo.IS_FOLIA) { + this.entityIdCache.remove(entity); + } + } + + @Override + public void removePassengers(Collection entities) { + this.passengers.removeAll(entities); + if (ServerInfo.IS_FOLIA) { + entities.forEach(this.entityIdCache::remove); + } + } + + @Override + public Set clearPassengers() { + HashSet set = new HashSet<>(this.passengers); + this.passengers.clear(); + if (ServerInfo.IS_FOLIA) { + this.entityIdCache.clear(); + } + + return set; + } + + public Collection getPassengerEntityIds() { + return Collections.unmodifiableCollection(this.entityIdCache.values()); + } + + @Override + public Set getPassengers() { + return ImmutableSet.copyOf(this.passengers); + } + + @Override + public boolean canMountMore() { + return !this.isDriver() || this.passengers.isEmpty(); + } + + @Override + public boolean isDriver() { + return this.driver; + } + + @Override + public Vector3f getLocation() { + return this.location; + } + + @Override + public Vector3f getGlobalLocation() { + return this.globalLocation; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/NameTagImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/NameTagImpl.java new file mode 100644 index 0000000..1296afb --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/NameTagImpl.java @@ -0,0 +1,215 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.type.NameTag; +import java.util.function.Supplier; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import org.bukkit.Location; +import org.bukkit.entity.Display.Billboard; +import org.bukkit.entity.TextDisplay.TextAlignment; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NameTagImpl extends AbstractBoneBehavior implements NameTag { + private static final String EMPTY_STRING = "{\"text\":\"\"}"; + private final Vector3f location = new Vector3f(); + private String jsonString = "{\"text\":\"\"}"; + private Supplier jsonStringSupplier; + private boolean visible; + private int backgroundColor = 1073741824; + private boolean useDefaultBackgroundColor = true; + private TextAlignment alignment = TextAlignment.CENTER; + private int lineWidth = 200; + private byte textOpacity = -1; + private boolean shadow = false; + private boolean seeThrough = true; + private Billboard billboard = Billboard.CENTER; + private Vector3f scale = new Vector3f(1.0F); + private Vector3f position = new Vector3f(0.0F); + + public NameTagImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + } + + @Override + public void onApply() { + Location baseLocation = this.bone.calculatePivotLocation(); + this.bone + .getBlueprintBone() + .getLocalPosition() + .rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location) + .add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ()); + } + + @Override + public void onFinalize() { + if (this.jsonStringSupplier != null) { + this.setJsonString(this.jsonStringSupplier.get()); + } + + Location baseLocation = this.bone.calculatePivotLocation(); + this.bone + .getGlobalTransform() + .mutatePosition( + vector3f -> vector3f.rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location) + .add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ()) + ); + } + + @Override + public void setString(String name) { + this.setComponent(Component.text(name)); + } + + @Override + public void setComponent(Component component) { + this.setJsonString((String)GsonComponentSerializer.gson().serialize(component)); + } + + @Override + public void setJsonString(String json) { + this.jsonString = json != null ? json : "{\"text\":\"\"}"; + } + + @Override + public void setComponentSupplier(@Nullable Supplier component) { + this.jsonStringSupplier = component == null ? null : () -> (String)GsonComponentSerializer.gson().serialize(component.get()); + } + + @Override + public void setUseDefaultBackgroundColor(boolean bool) { + this.useDefaultBackgroundColor = bool; + if (bool) { + this.backgroundColor = 1073741824; + } + } + + @Override + public Vector3f getLocation() { + return this.location; + } + + @Override + public String getJsonString() { + return this.jsonString; + } + + @Override + public Supplier getJsonStringSupplier() { + return this.jsonStringSupplier; + } + + @Override + public void setJsonStringSupplier(Supplier jsonStringSupplier) { + this.jsonStringSupplier = jsonStringSupplier; + } + + @Override + public boolean isVisible() { + return this.visible; + } + + @Override + public void setVisible(boolean visible) { + this.visible = visible; + } + + @Override + public int getBackgroundColor() { + return this.backgroundColor; + } + + @Override + public void setBackgroundColor(int backgroundColor) { + this.backgroundColor = backgroundColor; + } + + @Override + public boolean isUseDefaultBackgroundColor() { + return this.useDefaultBackgroundColor; + } + + @Override + public TextAlignment getAlignment() { + return this.alignment; + } + + @Override + public void setAlignment(TextAlignment alignment) { + this.alignment = alignment; + } + + @Override + public int getLineWidth() { + return this.lineWidth; + } + + @Override + public void setLineWidth(int lineWidth) { + this.lineWidth = lineWidth; + } + + @Override + public byte getTextOpacity() { + return this.textOpacity; + } + + @Override + public void setTextOpacity(byte textOpacity) { + this.textOpacity = textOpacity; + } + + @Override + public boolean isShadow() { + return this.shadow; + } + + @Override + public void setShadow(boolean shadow) { + this.shadow = shadow; + } + + @Override + public boolean isSeeThrough() { + return this.seeThrough; + } + + @Override + public void setSeeThrough(boolean seeThrough) { + this.seeThrough = seeThrough; + } + + @Override + public Billboard getBillboard() { + return this.billboard; + } + + @Override + public void setBillboard(Billboard billboard) { + this.billboard = billboard; + } + + @Override + public Vector3f getScale() { + return this.scale; + } + + @Override + public void setScale(Vector3f scale) { + this.scale = scale; + } + + @Override + public Vector3f getPosition() { + return this.position; + } + + @Override + public void setPosition(Vector3f position) { + this.position = position; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/PlayerLimbImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/PlayerLimbImpl.java new file mode 100644 index 0000000..b9cd466 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/PlayerLimbImpl.java @@ -0,0 +1,77 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.destroystokyo.paper.profile.PlayerProfile; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.events.BoneTransformReadEvent; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.type.PlayerLimb; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; +import org.jetbrains.annotations.Nullable; + +public class PlayerLimbImpl extends AbstractBoneBehavior implements PlayerLimb { + private final PlayerLimb.Limb limbType; + private boolean isSlim; + + public PlayerLimbImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + this.limbType = data.get("limb"); + } + + @Override + public void onApply() { + this.bone.setRenderer(true); + this.bone.setModel(new ItemStack(Material.AIR)); + } + + @Override + public void modifyTransform(BoneTransformReadEvent event) { + event.getPosition().add(0.0F, this.isSlim ? this.limbType.slimYOffset : this.limbType.defaultYOffset, 0.0F); + } + + @Override + public void setTexture(@Nullable Player player) { + if (player == null) { + this.bone.setModel(new ItemStack(Material.AIR)); + } else { + this.setTexture(player.getPlayerProfile()); + } + } + + @Override + public void setTexture(@Nullable PlayerProfile profile) { + if (profile == null) { + this.bone.setModel(new ItemStack(Material.AIR)); + } else { + ItemStack playerHead = new ItemStack(Material.PLAYER_HEAD); + ItemMeta meta = playerHead.getItemMeta(); + ((SkullMeta)meta).setPlayerProfile(profile); + + meta.setCustomModelData(switch (profile.getTextures().getSkinModel()) { + case CLASSIC -> { + this.isSlim = false; + yield this.limbType.defaultId; + } + case SLIM -> { + this.isSlim = true; + yield this.limbType.slimId; + } + default -> throw new IncompatibleClassChangeError(); + }); + playerHead.setItemMeta(meta); + ModelEngineAPI.getNMSHandler().applyPlayerHeadItemModel(playerHead); + this.bone.setModel(playerHead); + } + } + + @Override + public PlayerLimb.Limb getLimbType() { + return this.limbType; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/SegmentImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/SegmentImpl.java new file mode 100644 index 0000000..b1bbedc --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/SegmentImpl.java @@ -0,0 +1,51 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.utils.math.SafeTransform; +import org.bukkit.Location; +import org.joml.Vector3f; + +public class SegmentImpl extends AbstractSegmentImpl { + public SegmentImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + } + + @Override + public void onApply() { + super.onApply(); + if (this.backPivot) { + this.resetPivot(); + } + } + + @Override + public void onModelInitialized() { + super.onModelInitialized(); + if (!this.backPivot) { + this.resetPivot(); + } + } + + @Override + public void postGlobalCalculation() { + super.postGlobalCalculation(); + this.resetPivot(); + } + + @Override + public void postTransformDecompose() { + SafeTransform global = this.bone.getGlobalTransform(); + this.bone.getTransformMatrix().identity().rotate(global.getLeftQuaternion()).scale(global.getScale()).rotate(global.getRightQuaternion()); + global.mutatePosition(Vector3f::zero); + } + + private void resetPivot() { + this.bone.setPivotLocation(this.toLocation(this.worldLocation)); + } + + private Location toLocation(Vector3f vec) { + return this.bone.getBaseLocation().clone().set(vec.x, vec.y, vec.z); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/SubHitboxImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/SubHitboxImpl.java new file mode 100644 index 0000000..06c2452 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/SubHitboxImpl.java @@ -0,0 +1,226 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.api.utils.math.SafeTransform; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.ticker.DualTicker; +import java.util.Map; +import java.util.UUID; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class SubHitboxImpl extends AbstractBoneBehavior implements SubHitbox { + private final boolean isOBB; + private final Vector3f fixedDimension = new Vector3f(); + private final Vector3f origin = new Vector3f(); + private final Vector3f cubeRotation = new Vector3f(); + private final Vector3f cubeOrigin = new Vector3f(); + private final Vector3f scaledOrigin = new Vector3f(); + private final int hitboxId; + private final Vector3f dimension = new Vector3f(); + private final Vector3f location = new Vector3f(); + private final Quaternionf rotation = new Quaternionf(); + private final Map boundEntities = Maps.newConcurrentMap(); + private float yaw; + private HitboxEntity hitboxEntity; + private float damageMultiplier = 1.0F; + private boolean canBeHitByProjectile = true; + + public SubHitboxImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + Hitbox hitbox = data.get("dimension"); + if (hitbox == null) { + throw new RuntimeException("Unable to retrieve sub-hitbox dimension of bone " + bone.getUniqueBoneId()); + } else { + this.hitboxId = ModelEngineAPI.getEntityHandler().getNextEntityId(); + this.isOBB = data.get("obb", false); + Vector3f bonePosition = bone.getBlueprintBone().getGlobalPosition(); + this.origin.set(data.get("origin", bonePosition)).sub(bonePosition); + this.cubeRotation.set(data.get("rotation", this.cubeRotation)); + this.cubeOrigin.set(data.get("cube_origin", bonePosition)).sub(bonePosition); + this.origin.sub(this.cubeOrigin).rotateX(this.cubeRotation.x).rotateY(this.cubeRotation.y).rotateZ(this.cubeRotation.z).add(this.cubeOrigin); + if (this.isOBB) { + this.fixedDimension.set(hitbox.getWidth(), hitbox.getHeight(), hitbox.getDepth()); + } else { + this.fixedDimension.set(hitbox.getMaxWidth(), hitbox.getHeight(), hitbox.getMaxWidth()); + } + } + } + + @Override + public void onApply() { + Location baseLocation = this.bone.calculatePivotLocation(); + this.removeOld(); + this.hitboxEntity = ModelEngineAPI.getEntityHandler().createHitbox(baseLocation, this.bone, this); + this.bone + .getBlueprintBone() + .getLocalPosition() + .rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0), this.location) + .add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ()); + ModelEngineAPI.getInteractionTracker().setEntityRelay(this.hitboxId, this.hitboxEntity.getEntityId()); + } + + @Override + public void onRemove() { + ModelEngineAPI.getInteractionTracker().removeEntityRelay(this.hitboxId); + this.removeOld(); + DualTicker.queueSyncTask(() -> this.boundEntities.forEach((uuid, entity) -> entity.remove())); + } + + @Override + public void postAnimation() { + Vector3f localScale = this.bone.getLocalTransform().getScale(); + this.scaledOrigin.set(this.origin).mul(localScale); + this.bone.getLocalTransform().mutatePosition(vector3f -> vector3f.add(this.scaledOrigin)); + this.bone.getLocalTransform().mutateLeftQuaternion(quaternionf -> quaternionf.mul(TMath.toQuaternion(this.cubeRotation))); + } + + @Override + public void onFinalize() { + SafeTransform transform = this.bone.getGlobalTransform(); + this.location.set(transform.getPosition()).rotateY(-this.bone.getYaw() * (float) (Math.PI / 180.0)); + this.rotation.set(transform.getLeftQuaternion()).mul(transform.getRightQuaternion()).rotateLocalY(-this.bone.getYaw() * (float) (Math.PI / 180.0)); + transform.getScale().mul(this.fixedDimension, this.dimension); + this.dimension.mul(this.bone.getBlueprintBone().getScale()).mul(this.bone.getActiveModel().getScale()); + Location baseLocation = this.bone.calculatePivotLocation(); + this.location.add((float)baseLocation.getX(), (float)baseLocation.getY(), (float)baseLocation.getZ()); + if (!this.isOBB) { + this.location.sub(0.0F, this.dimension.y * 0.5F, 0.0F); + } + + if (this.hitboxEntity != null && !this.hitboxEntity.isValid()) { + this.hitboxEntity = null; + } + + if (this.hitboxEntity == null) { + this.hitboxEntity = ModelEngineAPI.getEntityHandler().createHitbox(baseLocation, this.bone, this); + if (this.hitboxEntity == null) { + return; + } + + ModelEngineAPI.getInteractionTracker().setEntityRelay(this.hitboxId, this.hitboxEntity.getEntityId()); + } + + this.hitboxEntity.queueLocation(new Vector3f(this.location)); + if (DebugToggle.isDebugging(DebugToggle.SHOW_OBB) && this.isOBB) { + OrientedBoundingBox obb = this.hitboxEntity.getOrientedBoundingBox(); + if (obb != null) { + obb.visualize(baseLocation.getWorld()); + } + } + } + + @Override + public void addBoundEntity(Entity entity) { + this.getBoundEntities().put(entity.getUniqueId(), entity); + ModelEngineAPI.getEntityHandler().forceDespawn(entity); + ModelEngineAPI.setRenderCanceled(entity.getEntityId(), true); + } + + @Override + public void removeBoundEntity(Entity entity) { + this.getBoundEntities().remove(entity.getUniqueId(), entity); + ModelEngineAPI.setRenderCanceled(entity.getEntityId(), false); + ModelEngineAPI.getEntityHandler().forceSpawn(entity); + } + + private void removeOld() { + if (this.hitboxEntity != null) { + this.hitboxEntity.markRemoved(); + } + } + + @Override + public boolean isOBB() { + return this.isOBB; + } + + @Override + public Vector3f getFixedDimension() { + return this.fixedDimension; + } + + @Override + public Vector3f getOrigin() { + return this.origin; + } + + public Vector3f getCubeRotation() { + return this.cubeRotation; + } + + public Vector3f getCubeOrigin() { + return this.cubeOrigin; + } + + public Vector3f getScaledOrigin() { + return this.scaledOrigin; + } + + @Override + public int getHitboxId() { + return this.hitboxId; + } + + @Override + public Vector3f getDimension() { + return this.dimension; + } + + @Override + public Vector3f getLocation() { + return this.location; + } + + @Override + public Quaternionf getRotation() { + return this.rotation; + } + + @Override + public Map getBoundEntities() { + return this.boundEntities; + } + + @Override + public float getYaw() { + return this.yaw; + } + + @Override + public HitboxEntity getHitboxEntity() { + return this.hitboxEntity; + } + + @Override + public float getDamageMultiplier() { + return this.damageMultiplier; + } + + @Override + public boolean isCanBeHitByProjectile() { + return this.canBeHitByProjectile; + } + + @Override + public void setDamageMultiplier(float damageMultiplier) { + this.damageMultiplier = damageMultiplier; + } + + @Override + public void setCanBeHitByProjectile(boolean canBeHitByProjectile) { + this.canBeHitByProjectile = canBeHitByProjectile; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/TailImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/TailImpl.java new file mode 100644 index 0000000..a324598 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/TailImpl.java @@ -0,0 +1,11 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; + +public class TailImpl extends AbstractSegmentImpl { + public TailImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/UserLimbImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/UserLimbImpl.java new file mode 100644 index 0000000..eeed9c3 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/behavior/UserLimbImpl.java @@ -0,0 +1,156 @@ +package com.ticxo.modelengine.core.model.bone.behavior; + +import com.destroystokyo.paper.profile.PlayerProfile; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.generator.skin.LimbData; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.AbstractBoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorData; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.type.UserLimb; +import com.ticxo.modelengine.api.utils.MojangAPI; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix4f; +import org.joml.Quaternionf; + +public class UserLimbImpl extends AbstractBoneBehavior implements UserLimb { + private final String limbType; + private final DataTracker generatedStack = new DataTracker<>(this.createHead(), ItemStack::isSimilar); + private LimbData limbData; + private boolean slim; + private final Matrix4f originalTransform = new Matrix4f(); + private boolean generating; + private volatile int generation; + private String placeholder; + + public UserLimbImpl(ModelBone bone, BoneBehaviorType type, BoneBehaviorData data) { + super(bone, type, data); + this.limbType = data.get("type"); + } + + @Override + public void onApply() { + this.bone.setRenderer(true); + this.bone.setModel(this.generatedStack.get()); + } + + @Override + public void preTransformDecompose() { + if (this.limbData != null) { + this.originalTransform.set(this.bone.getTransformMatrix()); + this.bone.getTransformMatrix().translate(this.limbData.translation()).rotate(new Quaternionf().rotateY((float) Math.PI)).scale(this.limbData.scale()); + } + } + + @Override + public void postTransformRecompose() { + this.bone.getTransformMatrix().set(this.originalTransform); + } + + @Override + public void onFinalize() { + this.generatedStack.ifDirty(this.bone::setModel); + this.generatedStack.clearDirty(); + } + + @Override + public void setTexture(@Nullable Player player) { + if (player == null) { + this.generatedStack.set(this.createHead()); + } else { + this.setTexture(player.getPlayerProfile()); + } + } + + @Override + public String getLimbType() { + return this.limbType; + } + + @Override + public void setStaticSkin(boolean slim, @Nullable String url) { + this.generation++; + this.slim = slim; + this.limbData = ModelEngineAPI.getAPI().getSkinSplitter().getLimb(this.limbType, slim); + if (url != null && this.limbData != null) { + this.generatedStack.set(this.limbData.createItem(url)); + } else { + this.generatedStack.set(this.createHead()); + } + } + + @Override + public void setTexture(@Nullable PlayerProfile profile) { + int gen = ++this.generation; + this.generatedStack.set(this.createHead()); + if (profile != null) { + switch (profile.getTextures().getSkinModel()) { + case CLASSIC: + this.slim = false; + break; + case SLIM: + this.slim = true; + } + + this.limbData = ModelEngineAPI.getAPI().getSkinSplitter().getLimb(this.limbType, this.slim); + if (this.limbData.isHead()) { + ItemStack head = this.createHead(); + head.editMeta(itemMeta -> ((SkullMeta)itemMeta).setPlayerProfile(profile)); + this.generatedStack.set(head); + } else { + this.generating = true; + ModelEngineAPI.getUserLimbRegistry() + .getSkinUrlFromKey(this.getPlaceholder(), this.limbType, this.slim) + .thenApply(url -> this.limbData.createItem(url)) + .handle((stack, throwable) -> { + if (throwable != null) { + throwable.printStackTrace(); + return null; + } else { + if (this.generating && gen == this.generation) { + this.generatedStack.set(stack); + } + + return null; + } + }); + MojangAPI.getRawSkinData(profile) + .thenCompose(base64 -> ModelEngineAPI.getUserLimbRegistry().getSkinUrlFromSource(base64, this.limbType, this.slim)) + .thenApply(url -> this.limbData.createItem(url)) + .handle((stack, throwable) -> { + if (throwable != null) { + throwable.printStackTrace(); + return null; + } else if (gen != this.generation) { + return null; + } else { + this.generatedStack.set(stack); + this.generating = false; + return null; + } + }); + } + } + } + + @Override + public String getPlaceholder() { + return this.placeholder != null + ? this.placeholder + : (this.slim ? ModelEngineAPI.getConfigCache().getSlim() : ModelEngineAPI.getConfigCache().getClassic()); + } + + private ItemStack createHead() { + return new ItemStack(Material.PLAYER_HEAD); + } + + @Override + public void setPlaceholder(String placeholder) { + this.placeholder = placeholder; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/LeashManagerImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/LeashManagerImpl.java new file mode 100644 index 0000000..2b08fdc --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/LeashManagerImpl.java @@ -0,0 +1,86 @@ +package com.ticxo.modelengine.core.model.bone.manager; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.AbstractBehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.LeashManager; +import com.ticxo.modelengine.api.model.bone.type.Leash; +import com.ticxo.modelengine.core.model.bone.behavior.LeashImpl; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import org.bukkit.entity.Entity; + +public class LeashManagerImpl extends AbstractBehaviorManager implements LeashManager { + private final Map main = new LinkedHashMap<>(); + private final Map leashes = new LinkedHashMap<>(); + + public LeashManagerImpl(ActiveModel activeModel, BoneBehaviorType type) { + super(activeModel, type); + } + + @Override + public void registerLeash(T leash) { + this.getLeashes().put(leash.getBone().getUniqueBoneId(), leash); + if (leash.isMainLeash()) { + this.getMainLeashes().put(leash.getBone().getUniqueBoneId(), leash); + } + } + + @Override + public Map getMainLeashes() { + return (Map)this.main; + } + + @Override + public Map getLeashes() { + return (Map)this.leashes; + } + + @Override + public Optional getLeash(String boneId) { + return Optional.ofNullable(this.getLeashes().get(boneId)); + } + + @Override + public void connectMainLeashes(Entity leashHolder) { + this.getMainLeashes().values().forEach(leash -> ((Leash)leash).connect(leashHolder)); + } + + @Override + public void connectMainLeashes(String from) { + this.getLeash(from).ifPresent(leash -> this.getMainLeashes().values().forEach(mainLeash -> ((Leash)mainLeash).connect(leash))); + } + + @Override + public void disconnectMainLeashes() { + this.getMainLeashes().values().forEach(rec$ -> ((Leash)rec$).disconnect()); + } + + @Override + public void connectLeash(Entity leashHolder, String to) { + this.getLeash(to).ifPresent(leash -> ((Leash)leash).connect(leashHolder)); + } + + @Override + public void connectLeash(String from, String to) { + this.getLeash(to).ifPresent(toLeash -> this.getLeash(from).ifPresent(fromLeash -> ((Leash)toLeash).connect(fromLeash))); + } + + @Override + public void disconnect(String bone) { + this.getLeash(bone).ifPresent(rec$ -> ((Leash)rec$).disconnect()); + } + + @Override + public Entity getLeashHolder(String bone) { + return this.getLeash(bone).map(rec$ -> ((Leash)rec$).getConnectedEntity()).orElse(null); + } + + @Override + public T getLeashConnection(String bone) { + Optional leash = this.getLeash(bone); + return leash.isPresent() ? leash.get().getConnectedLeash() : null; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/MountDataImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/MountDataImpl.java new file mode 100644 index 0000000..f317c3d --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/MountDataImpl.java @@ -0,0 +1,21 @@ +package com.ticxo.modelengine.core.model.bone.manager; + +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; + +public class MountDataImpl implements GlobalBehaviorData, MountData { + private MountManager mainMountManager; + + @Override + public & MountManager> T getMainMountManager() { + return (T)this.mainMountManager; + } + + @Override + public & MountManager> void setMainMountManager(T manager) { + this.mainMountManager = manager; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/MountManagerImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/MountManagerImpl.java new file mode 100644 index 0000000..7987772 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/manager/MountManagerImpl.java @@ -0,0 +1,497 @@ +package com.ticxo.modelengine.core.model.bone.manager; + +import com.google.common.collect.ImmutableMap; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.events.ModelDismountEvent; +import com.ticxo.modelengine.api.events.ModelMountEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.AbstractBehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.mount.controller.MountControllerSupplier; +import com.ticxo.modelengine.api.utils.data.io.SavedData; +import com.ticxo.modelengine.core.model.bone.behavior.MountImpl; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Consumer; +import org.bukkit.entity.Entity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class MountManagerImpl extends AbstractBehaviorManager implements MountManager { + private final Map seats = new LinkedHashMap<>(); + private final Map passengerSeatMap = new HashMap<>(); + boolean canDrive; + boolean canRide; + private Entity driver; + private Mount driverBone; + + public MountManagerImpl(ActiveModel activeModel, BoneBehaviorType supplier) { + super(activeModel, supplier); + } + + @Override + public void onDestroy() { + this.dismountDriver(); + this.dismountAll(); + } + + @Override + public void load(SavedData data) { + this.canDrive = data.getBoolean("drive"); + this.canRide = data.getBoolean("ride"); + } + + @Override + public void save(SavedData data) { + data.putBoolean("drive", this.canDrive); + data.putBoolean("ride", this.canRide); + } + + @Override + public boolean canDrive() { + return this.canDrive; + } + + @Override + public boolean canRide() { + return this.canRide; + } + + @Override + public boolean isControlled() { + return this.driver != null && this.driverBone != null; + } + + @Override + public boolean hasPassengers() { + return !this.passengerSeatMap.isEmpty(); + } + + @Override + public boolean hasRiders() { + return this.driver != null || !this.passengerSeatMap.isEmpty(); + } + + @Nullable + @Override + public T getDriverBone() { + return (T)this.driverBone; + } + + @Override + public void setDriverBone(@Nullable T mount) { + this.driverBone = mount; + } + + @Override + public void registerSeat(T mount) { + this.getSeats().put(mount.getBone().getUniqueBoneId(), mount); + } + + @Override + public Map getSeats() { + return (Map)this.seats; + } + + @Override + public Optional getSeat(String boneId) { + if (boneId == null) { + return Optional.empty(); + } else { + Map seats = this.getSeats(); + BoneBehavior seat = (BoneBehavior)seats.get(boneId); + if (seat == null && boneId.startsWith("p_")) { + seat = (BoneBehavior)seats.get(boneId.substring(2)); + } + + return Optional.ofNullable((T)seat); + } + } + + @Override + public Optional getMount(Entity entity) { + if (entity == this.driver) { + return Optional.ofNullable(this.getDriverBone()); + } else { + Mount mount = this.passengerSeatMap.get(entity); + return Optional.ofNullable((T)mount); + } + } + + @Override + public Map getPassengerSeatMap() { + return ImmutableMap.copyOf(this.passengerSeatMap); + } + + @Override + public boolean mountDriver(Entity entity, MountControllerSupplier supplier) { + return this.mountDriver(entity, supplier, null); + } + + @Override + public boolean mountDriver(Entity entity, MountControllerSupplier supplier, @Nullable Consumer consumer) { + if (this.driverBone != null && this.driverBone.getPassengers().isEmpty() && this.canDrive()) { + ModelMountEvent event = new ModelMountEvent(this.activeModel, entity, true, this.driverBone); + ModelEngineAPI.callEvent(event); + if (event.isCancelled()) { + return false; + } else { + boolean success = this.driverBone.addPassenger(entity); + if (success) { + this.driver = entity; + this.registerMountPair(entity, this.driverBone, supplier, consumer); + } + + return success; + } + } else { + return false; + } + } + + @Override + public boolean mountPassenger(String boneId, Entity entity, MountControllerSupplier supplier) { + return this.mountPassenger(boneId, entity, supplier, null); + } + + @Override + public boolean mountPassenger(String boneId, Entity entity, MountControllerSupplier supplier, @Nullable Consumer consumer) { + return this.canRide() && this.getSeat(boneId).map(mount -> this.mountPassenger((Mount)mount, entity, supplier, consumer)).orElse(false); + } + + @Override + public boolean mountPassenger(Mount mount, Entity entity, MountControllerSupplier supplier) { + return this.mountPassenger(mount, entity, supplier, null); + } + + @Override + public boolean mountPassenger(Mount mount, Entity entity, MountControllerSupplier supplier, @Nullable Consumer consumer) { + ModelMountEvent event = new ModelMountEvent(this.activeModel, entity, false, mount); + ModelEngineAPI.callEvent(event); + if (event.isCancelled()) { + return false; + } else { + boolean success = mount.addPassenger(entity); + if (success) { + this.passengerSeatMap.put(entity, mount); + this.registerMountPair(entity, mount, supplier, consumer); + } + + return success; + } + } + + @Override + public boolean mountAvailable(Entity entity, MountControllerSupplier supplier) { + return this.mountAvailable(entity, supplier, null); + } + + @Override + public boolean mountAvailable(Entity entity, MountControllerSupplier supplier, @Nullable Consumer consumer) { + return this.mountAvailable(entity, this.seats.keySet(), supplier, consumer); + } + + @Override + public Set mountAvailable(Collection entities, MountControllerSupplier supplier) { + return this.mountAvailable(entities, supplier, null); + } + + @Override + public Set mountAvailable(Collection entities, MountControllerSupplier supplier, @Nullable Consumer consumer) { + return this.mountAvailable(entities, this.seats.keySet(), supplier, consumer); + } + + @Override + public boolean mountAvailable(Entity entity, Collection seats, MountControllerSupplier supplier) { + return this.mountAvailable(entity, seats, supplier, null); + } + + @Override + public boolean mountAvailable(Entity entity, Collection seats, MountControllerSupplier supplier, @Nullable Consumer consumer) { + for (String seatId : seats) { + Optional maybeSeat = this.getSeat(seatId); + if (!maybeSeat.isEmpty()) { + BoneBehavior seat = (BoneBehavior)maybeSeat.get(); + if (((Mount)seat).getPassengers().isEmpty()) { + this.mountPassenger((Mount)seat, entity, supplier, consumer); + return true; + } + } + } + + return false; + } + + @Override + public Set mountAvailable(Collection entities, Collection seats, MountControllerSupplier supplier) { + return this.mountAvailable(entities, seats, supplier, null); + } + + @Override + public Set mountAvailable( + Collection entities, Collection seats, MountControllerSupplier supplier, @Nullable Consumer consumer + ) { + HashSet unseated = new HashSet<>(); + boolean noSeats = false; + + label30: + for (Entity entity : entities) { + if (!noSeats) { + noSeats = true; + + for (String seatId : seats) { + Optional maybeSeat = this.getSeat(seatId); + if (!maybeSeat.isEmpty()) { + BoneBehavior seat = (BoneBehavior)maybeSeat.get(); + if (((Mount)seat).getPassengers().isEmpty()) { + this.mountPassenger((Mount)seat, entity, supplier, consumer); + noSeats = false; + continue label30; + } + } + } + } + + unseated.add(entity); + } + + return unseated; + } + + @Override + public boolean mountLeastOccupied(Entity entity, MountControllerSupplier supplier) { + return this.mountLeastOccupied(entity, supplier, null); + } + + @Override + public boolean mountLeastOccupied(Entity entity, MountControllerSupplier supplier, @Nullable Consumer consumer) { + return this.mountLeastOccupied(entity, this.seats.keySet(), supplier, consumer); + } + + @Override + public Set mountLeastOccupied(Collection entities, MountControllerSupplier supplier) { + return this.mountLeastOccupied(entities, supplier, null); + } + + @Override + public Set mountLeastOccupied(Collection entities, MountControllerSupplier supplier, @Nullable Consumer consumer) { + return this.mountLeastOccupied(entities, this.seats.keySet(), supplier, consumer); + } + + @Override + public boolean mountLeastOccupied(Entity entity, Collection seats, MountControllerSupplier supplier) { + return this.mountLeastOccupied(entity, seats, supplier, null); + } + + @Override + public boolean mountLeastOccupied(Entity entity, Collection seats, MountControllerSupplier supplier, @Nullable Consumer consumer) { + int leastCount = Integer.MAX_VALUE; + Mount leastOccupied = null; + + for (String seatId : seats) { + Optional maybeSeat = this.getSeat(seatId); + if (!maybeSeat.isEmpty()) { + BoneBehavior seat = (BoneBehavior)maybeSeat.get(); + if (((Mount)seat).canMountMore()) { + int count = ((Mount)seat).getPassengers().size(); + if (count == 0) { + return this.mountPassenger((Mount)seat, entity, supplier, consumer); + } + + if (leastCount > count) { + leastCount = count; + leastOccupied = (Mount)seat; + } + } + } + } + + return leastOccupied != null ? this.mountPassenger(leastOccupied, entity, supplier, consumer) : false; + } + + @Override + public Set mountLeastOccupied(Collection entities, Collection seats, MountControllerSupplier supplier) { + return this.mountLeastOccupied(entities, seats, supplier, null); + } + + @Override + public Set mountLeastOccupied( + Collection entities, Collection seats, MountControllerSupplier supplier, @Nullable Consumer consumer + ) { + HashSet set = new HashSet<>(); + + for (Entity entity : entities) { + if (!this.mountLeastOccupied(entity, seats, supplier, consumer)) { + set.add(entity); + } + } + + return set; + } + + @Override + public Entity dismountDriver() { + if (this.driverBone != null && this.driver != null) { + ModelDismountEvent event = new ModelDismountEvent(this.activeModel, this.driver, true, this.driverBone); + ModelEngineAPI.callEvent(event); + if (event.isCancelled()) { + return null; + } else { + this.driverBone.removePassenger(this.driver); + this.flushMountPassengerUpdate(this.driverBone); + this.removeMountPair(this.driver); + Entity t = this.driver; + this.driver = null; + return t; + } + } else { + return null; + } + } + + @Override + public void dismountPassenger(@NotNull Entity entity) { + Mount mount = this.passengerSeatMap.remove(entity); + if (mount != null) { + ModelDismountEvent event = new ModelDismountEvent(this.activeModel, entity, false, mount); + ModelEngineAPI.callEvent(event); + if (event.isCancelled()) { + return; + } + + mount.removePassenger(entity); + this.flushMountPassengerUpdate(mount); + this.removeMountPair(entity); + } + } + + @Override + public void dismountRider(@NotNull Entity entity) { + if (entity == this.driver) { + this.dismountDriver(); + } else { + this.dismountPassenger(entity); + } + } + + @Override + public Set dismountPassengers(String boneId) { + HashSet removed = new HashSet<>(); + this.getSeat(boneId).ifPresent(mount -> { + for (Entity entity : ((Mount)mount).getPassengers()) { + ModelDismountEvent event = new ModelDismountEvent(this.activeModel, entity, false, (Mount)mount); + ModelEngineAPI.callEvent(event); + if (!event.isCancelled()) { + ((Mount)mount).removePassenger(entity); + this.removeMountPair(entity); + removed.add(entity); + } + } + + if (!removed.isEmpty()) { + this.flushMountPassengerUpdate((Mount)mount); + } + }); + return removed; + } + + @Override + public Set dismountAll() { + HashSet set = new HashSet<>(); + + for (BoneBehavior val : this.getSeats().values()) { + Set passengers = ((Mount)val).clearPassengers(); + boolean anyDismounted = false; + + for (Entity entity : passengers) { + ModelDismountEvent event = new ModelDismountEvent(this.activeModel, entity, false, (Mount)val); + ModelEngineAPI.callEvent(event); + if (!event.isCancelled()) { + this.passengerSeatMap.remove(entity); + this.removeMountPair(entity); + set.add(entity); + anyDismounted = true; + } + } + + if (anyDismounted) { + this.flushMountPassengerUpdate((Mount)val); + } + } + + return set; + } + + private void registerMountPair(Entity entity, Mount mount, MountControllerSupplier supplier, @Nullable Consumer consumer) { + MountController controller = supplier.createController(entity, mount); + if (consumer != null) { + consumer.accept(controller); + } + + ModelEngineAPI.getMountPairManager().registerMountedPair(entity, this.activeModel, controller); + this.activeModel.getModeledEntity().getBase().setCollidableWith(entity, false); + } + + private void removeMountPair(Entity entity) { + ModelEngineAPI.getMountPairManager().unregisterMountedPair(entity.getUniqueId()); + this.activeModel.getModeledEntity().getBase().setCollidableWith(entity, true); + } + + private void flushMountPassengerUpdate(Mount mount) { + if (mount instanceof BoneBehavior behavior) { + String boneId = behavior.getBone().getUniqueBoneId(); + this.activeModel.getBehaviorRenderer(BoneBehaviorTypes.MOUNT).ifPresent(renderer -> { + if (renderer instanceof MountRenderer mountRenderer) { + MountRenderer.Mount renderedMount = mountRenderer.getRendered().get(boneId); + if (renderedMount == null) { + renderedMount = mountRenderer.getSpawnQueue().get(boneId); + } + + if (renderedMount != null) { + HashSet newIds = new HashSet<>(); + if (ServerInfo.IS_FOLIA && mount instanceof MountImpl mountImpl) { + newIds.addAll(mountImpl.getPassengerEntityIds()); + } else { + for (Entity entity : mount.getPassengers()) { + newIds.add(entity.getEntityId()); + } + } + + renderedMount.getPassengers().retainAll(newIds); + renderedMount.getPassengers().addAll(newIds); + Set targets = this.activeModel.getModeledEntity().getBase().getData().getTracking().keySet(); + ModelEngineAPI.getNMSHandler().sendMountPassengerUpdate(targets, renderedMount.getMountId(), renderedMount.getPassengers().get()); + } + } + }); + } + } + + @Override + public void setCanDrive(boolean canDrive) { + this.canDrive = canDrive; + } + + @Override + public void setCanRide(boolean canRide) { + this.canRide = canRide; + } + + @Override + public Entity getDriver() { + return this.driver; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/AbstractBehaviorRenderer.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/AbstractBehaviorRenderer.java new file mode 100644 index 0000000..26e4263 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/AbstractBehaviorRenderer.java @@ -0,0 +1,32 @@ +package com.ticxo.modelengine.core.model.bone.render; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.nms.NMSHandler; + +public abstract class AbstractBehaviorRenderer implements BehaviorRenderer { + protected final ActiveModel activeModel; + protected final NMSHandler nmsHandler = ModelEngineAPI.getNMSHandler(); + protected ModelRenderer modelRenderer; + + public AbstractBehaviorRenderer(ActiveModel activeModel) { + this.activeModel = activeModel; + } + + @Override + public ActiveModel getActiveModel() { + return this.activeModel; + } + + @Override + public ModelRenderer getModelRenderer() { + return this.modelRenderer; + } + + @Override + public void setModelRenderer(ModelRenderer modelRenderer) { + this.modelRenderer = modelRenderer; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/HeldItemRendererImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/HeldItemRendererImpl.java new file mode 100644 index 0000000..b0a1151 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/HeldItemRendererImpl.java @@ -0,0 +1,239 @@ +package com.ticxo.modelengine.core.model.bone.render; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.model.bone.type.HeldItem; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.bukkit.inventory.ItemStack; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HeldItemRendererImpl extends AbstractBehaviorRenderer implements HeldItemRenderer { + private final int id; + private final UUID uuid; + private final Map spawnQueue = new HashMap<>(); + private final Map rendered = new HashMap<>(); + private final Map destroyQueue = new HashMap<>(); + private final CollectionDataTracker passengers = new CollectionDataTracker<>(new HashSet<>()); + private final PositionCodec positionCodec = new PositionCodec(); + private boolean initialized; + private BehaviorRendererParser cachedParser; + private RenderParsers cachedParserOwner; + + public HeldItemRendererImpl(ActiveModel activeModel) { + super(activeModel); + this.id = this.nmsHandler.getEntityHandler().getNextEntityId(); + this.uuid = UUID.randomUUID(); + } + + @Override + public void initialize() { + for (Entry boneEntry : this.activeModel.getBones().entrySet()) { + String boneId = boneEntry.getKey(); + ModelBone modelBone = boneEntry.getValue(); + this.create(boneId, modelBone); + } + + this.initialized = true; + } + + private void create(String boneId, ModelBone modelBone) { + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM); + if (!maybeData.isEmpty()) { + BoneBehavior itemData = (BoneBehavior)maybeData.get(); + HeldItemRendererImpl.ItemImpl item = new HeldItemRendererImpl.ItemImpl(this.nmsHandler.getEntityHandler().getNextEntityId(), UUID.randomUUID()); + item.position.set(((HeldItem)itemData).getLocation()); + item.scale.set(modelBone.getGlobalTransform().getScale()); + item.rotation.set(((HeldItem)itemData).getRotation()); + item.model.set(modelBone.isVisible() ? modelBone.getModel() : null); + item.display.set(((HeldItem)itemData).getDisplay()); + item.glowing.set(modelBone.isGlowing()); + item.glowColor.set(modelBone.getGlowColor()); + this.spawnQueue.put(boneId, item); + this.destroyQueue.remove(boneId); + this.passengers.add(item.id); + } + } + + @Override + public void readBoneData() { + if (this.initialized) { + this.destroyQueue.putAll(this.rendered); + + for (Entry boneEntry : this.activeModel.getBones().entrySet()) { + String boneId = boneEntry.getKey(); + ModelBone modelBone = boneEntry.getValue(); + HeldItemRenderer.Item renderer = this.getQueued(boneId); + if (renderer != null) { + this.read(boneId, renderer, modelBone); + } else { + this.create(boneId, modelBone); + } + } + + this.destroyQueue.forEach((s, item) -> this.passengers.remove(item.getId())); + } + } + + private void read(String boneId, HeldItemRenderer.Item item, ModelBone modelBone) { + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM); + maybeData.ifPresent(heldItem -> { + item.getPosition().set(((HeldItem)heldItem).getLocation()); + item.getScale().set(modelBone.getGlobalTransform().getScale()); + item.getRotation().set(((HeldItem)heldItem).getRotation()); + item.getGlowing().set(modelBone.isGlowing()); + item.getGlowColor().set(modelBone.getGlowColor()); + if (!modelBone.isVisible()) { + item.getModel().set(null); + } else { + item.getModel().set(modelBone.getModel()); + if (modelBone.getModelTracker().isDirty()) { + modelBone.getModelTracker().clearDirty(); + item.getModel().markDirty(); + } + } + + item.getDisplay().set(((HeldItem)heldItem).getDisplay()); + this.destroyQueue.remove(boneId); + }); + } + + @Override + public void sendToClient(RenderParsers parsers) { + if (this.initialized) { + this.destroyQueue.keySet().forEach(this.rendered::remove); + this.parser(parsers).sendToClients(this); + this.rendered.putAll(this.spawnQueue); + this.spawnQueue.clear(); + this.destroyQueue.clear(); + } + } + + @Override + public void destroy(RenderParsers parsers) { + if (this.initialized) { + parsers.getBehaviorParser(this).destroy(this); + } + } + + private BehaviorRendererParser parser(RenderParsers parsers) { + if (this.cachedParser == null || this.cachedParserOwner != parsers) { + this.cachedParserOwner = parsers; + this.cachedParser = parsers.getBehaviorParser(this); + } + + return this.cachedParser; + } + + @Override + public int getId() { + return this.id; + } + + @Override + public UUID getUuid() { + return this.uuid; + } + + @Override + public Map getSpawnQueue() { + return this.spawnQueue; + } + + @Override + public Map getRendered() { + return this.rendered; + } + + @Override + public Map getDestroyQueue() { + return this.destroyQueue; + } + + @Override + public CollectionDataTracker getPassengers() { + return this.passengers; + } + + @Override + public PositionCodec getPositionCodec() { + return this.positionCodec; + } + + public static class ItemImpl implements HeldItemRenderer.Item { + private final int id; + private final UUID uuid; + private final DataTracker position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final DataTracker scale = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final DataTracker rotation = new UpdateDataTracker<>(new Quaternionf(), Quaternionf::set); + private final DataTracker model = new DataTracker<>(); + private final DataTracker display = new DataTracker<>(ItemDisplayTransform.NONE); + private final DataTracker glowing = new DataTracker<>(false); + private final DataTracker glowColor = new DataTracker<>(-1); + + @Override + public int getId() { + return this.id; + } + + @Override + public UUID getUuid() { + return this.uuid; + } + + @Override + public DataTracker getPosition() { + return this.position; + } + + @Override + public DataTracker getScale() { + return this.scale; + } + + @Override + public DataTracker getRotation() { + return this.rotation; + } + + @Override + public DataTracker getModel() { + return this.model; + } + + @Override + public DataTracker getDisplay() { + return this.display; + } + + @Override + public DataTracker getGlowing() { + return this.glowing; + } + + @Override + public DataTracker getGlowColor() { + return this.glowColor; + } + + public ItemImpl(int id, UUID uuid) { + this.id = id; + this.uuid = uuid; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/LeashRendererImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/LeashRendererImpl.java new file mode 100644 index 0000000..9a6e8bb --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/LeashRendererImpl.java @@ -0,0 +1,193 @@ +package com.ticxo.modelengine.core.model.bone.render; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import org.bukkit.entity.Entity; +import org.joml.Vector3f; + +public class LeashRendererImpl extends AbstractBehaviorRenderer implements LeashRenderer { + private final Map spawnQueue = new HashMap<>(); + private final Map rendered = new HashMap<>(); + private final Map destroyQueue = new HashMap<>(); + private boolean initialized; + private BehaviorRendererParser cachedParser; + private RenderParsers cachedParserOwner; + + public LeashRendererImpl(ActiveModel activeModel) { + super(activeModel); + } + + @Override + public void initialize() { + for (Entry boneEntry : this.activeModel.getBones().entrySet()) { + String boneId = boneEntry.getKey(); + ModelBone modelBone = boneEntry.getValue(); + this.create(boneId, modelBone); + } + + this.initialized = true; + } + + private void create(String boneId, ModelBone modelBone) { + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.LEASH); + if (!maybeData.isEmpty()) { + BoneBehavior leashData = (BoneBehavior)maybeData.get(); + LeashRendererImpl.LeashImpl leash = new LeashRendererImpl.LeashImpl( + this.nmsHandler.getEntityHandler().getNextEntityId(), ((com.ticxo.modelengine.api.model.bone.type.Leash)leashData).getId() + ); + leash.position.set(((com.ticxo.modelengine.api.model.bone.type.Leash)leashData).getLocation()); + leash.connected.set(this.getConnectedId((com.ticxo.modelengine.api.model.bone.type.Leash)leashData)); + this.spawnQueue.put(boneId, leash); + this.destroyQueue.remove(boneId); + ModelEngineAPI.getInteractionTracker().setModelRelay(leash.getLeashId(), this.activeModel); + } + } + + @Override + public void readBoneData() { + if (this.initialized) { + this.destroyQueue.putAll(this.rendered); + + for (Entry boneEntry : this.activeModel.getBones().entrySet()) { + String boneId = boneEntry.getKey(); + ModelBone modelBone = boneEntry.getValue(); + LeashRenderer.Leash renderer = this.getQueued(boneId); + if (renderer != null) { + this.read(boneId, renderer, modelBone); + } else { + this.create(boneId, modelBone); + } + } + } + } + + private void read(String boneId, LeashRenderer.Leash leash, ModelBone modelBone) { + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.LEASH); + maybeData.ifPresent(leashData -> { + leash.getPosition().set(((com.ticxo.modelengine.api.model.bone.type.Leash)leashData).getLocation()); + leash.getConnected().set(this.getConnectedId((com.ticxo.modelengine.api.model.bone.type.Leash)leashData)); + this.destroyQueue.remove(boneId); + }); + } + + @Override + public void sendToClient(RenderParsers parsers) { + if (this.initialized) { + this.destroyQueue.keySet().forEach(this.rendered::remove); + this.parser(parsers).sendToClients(this); + this.destroyQueue.values().forEach(leash -> ModelEngineAPI.getInteractionTracker().removeModelRelay(leash.getLeashId())); + this.rendered.putAll(this.spawnQueue); + this.spawnQueue.clear(); + this.destroyQueue.clear(); + } + } + + @Override + public void destroy(RenderParsers parsers) { + if (this.initialized) { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + this.rendered.values().forEach(leash -> tracker.removeModelRelay(leash.getLeashId())); + this.spawnQueue.values().forEach(leash -> tracker.removeModelRelay(leash.getLeashId())); + parsers.getBehaviorParser(this).destroy(this); + } + } + + private int getConnectedId(com.ticxo.modelengine.api.model.bone.type.Leash leash) { + Entity entity = leash.getConnectedEntity(); + if (entity != null) { + return entity.getEntityId(); + } else { + var other = (BoneBehavior & com.ticxo.modelengine.api.model.bone.type.Leash)leash.getConnectedLeash(); + return other != null ? ((com.ticxo.modelengine.api.model.bone.type.Leash)other).getId() : -1; + } + } + + private BehaviorRendererParser parser(RenderParsers parsers) { + if (this.cachedParser == null || this.cachedParserOwner != parsers) { + this.cachedParserOwner = parsers; + this.cachedParser = parsers.getBehaviorParser(this); + } + + return this.cachedParser; + } + + @Override + public Map getSpawnQueue() { + return this.spawnQueue; + } + + @Override + public Map getRendered() { + return this.rendered; + } + + @Override + public Map getDestroyQueue() { + return this.destroyQueue; + } + + public static class LeashImpl implements LeashRenderer.Leash { + private final int pivotId; + private final UUID pivotUUID = UUID.randomUUID(); + private final int leashId; + private final UUID leastUUID = UUID.randomUUID(); + private final DataTracker position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final DataTracker connected = new DataTracker<>(); + private final PositionCodec positionCodec = new PositionCodec(); + + public LeashImpl(int pivotId, int leashId) { + this.pivotId = pivotId; + this.leashId = leashId; + } + + @Override + public int getPivotId() { + return this.pivotId; + } + + @Override + public UUID getPivotUUID() { + return this.pivotUUID; + } + + @Override + public int getLeashId() { + return this.leashId; + } + + @Override + public UUID getLeastUUID() { + return this.leastUUID; + } + + @Override + public DataTracker getPosition() { + return this.position; + } + + @Override + public DataTracker getConnected() { + return this.connected; + } + + @Override + public PositionCodec getPositionCodec() { + return this.positionCodec; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/MountRendererImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/MountRendererImpl.java new file mode 100644 index 0000000..1c7e012 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/MountRendererImpl.java @@ -0,0 +1,217 @@ +package com.ticxo.modelengine.core.model.bone.render; + +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.core.model.bone.behavior.MountImpl; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import org.bukkit.entity.Entity; +import org.joml.Vector3f; + +public class MountRendererImpl extends AbstractBehaviorRenderer implements MountRenderer { + private final Map spawnQueue = new HashMap<>(); + private final Map rendered = new HashMap<>(); + private final Map destroyQueue = new HashMap<>(); + private boolean initialized; + private BehaviorRendererParser cachedParser; + private RenderParsers cachedParserOwner; + + public MountRendererImpl(ActiveModel activeModel) { + super(activeModel); + } + + @Override + public void initialize() { + for (Entry boneEntry : this.activeModel.getBones().entrySet()) { + String boneId = boneEntry.getKey(); + ModelBone modelBone = boneEntry.getValue(); + this.create(boneId, modelBone); + } + + this.initialized = true; + } + + private void create(String boneId, ModelBone modelBone) { + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.MOUNT); + if (!maybeData.isEmpty()) { + BoneBehavior mountData = (BoneBehavior)maybeData.get(); + MountRendererImpl.MountRenderData mount = new MountRendererImpl.MountRenderData( + this.nmsHandler.getEntityHandler().getNextEntityId(), UUID.randomUUID(), this.nmsHandler.getEntityHandler().getNextEntityId(), UUID.randomUUID() + ); + mount.position.set(((com.ticxo.modelengine.api.model.bone.type.Mount)mountData).getGlobalLocation()); + mount.yaw.set(TMath.rotToByte(modelBone.getYaw())); + mount.health.set(modelBone.getActiveModel().getModeledEntity().getBase().getHealth()); + mount.maxHealth.set(modelBone.getActiveModel().getModeledEntity().getBase().getMaxHealth()); + if (ServerInfo.IS_FOLIA && mountData instanceof MountImpl mountImpl) { + mount.passengers.get().addAll(mountImpl.getPassengerEntityIds()); + } else { + for (Entity entity : ((com.ticxo.modelengine.api.model.bone.type.Mount)mountData).getPassengers()) { + mount.passengers.get().add(entity.getEntityId()); + } + } + + this.spawnQueue.put(boneId, mount); + this.destroyQueue.remove(boneId); + } + } + + @Override + public void readBoneData() { + if (this.initialized) { + this.destroyQueue.putAll(this.rendered); + + for (Entry boneEntry : this.activeModel.getBones().entrySet()) { + String boneId = boneEntry.getKey(); + ModelBone modelBone = boneEntry.getValue(); + MountRenderer.Mount renderer = this.getQueued(boneId); + if (renderer != null) { + this.read(boneId, renderer, modelBone); + } else { + this.create(boneId, modelBone); + } + } + } + } + + private void read(String boneId, MountRenderer.Mount mount, ModelBone modelBone) { + mount.getYaw().set(TMath.rotToByte(modelBone.getYaw())); + mount.getHealth().set(modelBone.getActiveModel().getModeledEntity().getBase().getHealth()); + mount.getMaxHealth().set(modelBone.getActiveModel().getModeledEntity().getBase().getMaxHealth()); + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.MOUNT); + maybeData.ifPresent(mountData -> { + mount.getPosition().set(((com.ticxo.modelengine.api.model.bone.type.Mount)mountData).getGlobalLocation()); + HashSet newIds = new HashSet<>(); + if (ServerInfo.IS_FOLIA && mountData instanceof MountImpl mountImpl) { + newIds.addAll(mountImpl.getPassengerEntityIds()); + } else { + for (Entity entity : ((com.ticxo.modelengine.api.model.bone.type.Mount)mountData).getPassengers()) { + newIds.add(entity.getEntityId()); + } + } + + mount.getPassengers().retainAll(newIds); + mount.getPassengers().addAll(newIds); + this.destroyQueue.remove(boneId); + }); + } + + @Override + public void sendToClient(RenderParsers parsers) { + if (this.initialized) { + this.destroyQueue.keySet().forEach(this.rendered::remove); + this.parser(parsers).sendToClients(this); + this.rendered.putAll(this.spawnQueue); + this.spawnQueue.clear(); + this.destroyQueue.clear(); + } + } + + @Override + public void destroy(RenderParsers parsers) { + if (this.initialized) { + parsers.getBehaviorParser(this).destroy(this); + } + } + + private BehaviorRendererParser parser(RenderParsers parsers) { + if (this.cachedParser == null || this.cachedParserOwner != parsers) { + this.cachedParserOwner = parsers; + this.cachedParser = parsers.getBehaviorParser(this); + } + + return this.cachedParser; + } + + @Override + public Map getSpawnQueue() { + return this.spawnQueue; + } + + @Override + public Map getRendered() { + return this.rendered; + } + + @Override + public Map getDestroyQueue() { + return this.destroyQueue; + } + + public static class MountRenderData implements MountRenderer.Mount { + private final int pivotId; + private final UUID pivotUuid; + private final int mountId; + private final UUID mountUuid; + private final DataTracker position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final DataTracker health = new DataTracker<>(20.0F); + private final DataTracker maxHealth = new DataTracker<>(20.0F); + private final DataTracker yaw = new DataTracker<>((byte)0); + private final CollectionDataTracker passengers = new CollectionDataTracker<>(new HashSet<>()); + + public MountRenderData(int pivotId, UUID pivotUuid, int mountId, UUID mountUuid) { + this.pivotId = pivotId; + this.pivotUuid = pivotUuid; + this.mountId = mountId; + this.mountUuid = mountUuid; + } + + @Override + public int getPivotId() { + return this.pivotId; + } + + @Override + public UUID getPivotUuid() { + return this.pivotUuid; + } + + @Override + public int getMountId() { + return this.mountId; + } + + @Override + public UUID getMountUuid() { + return this.mountUuid; + } + + @Override + public DataTracker getPosition() { + return this.position; + } + + @Override + public DataTracker getHealth() { + return this.health; + } + + @Override + public DataTracker getMaxHealth() { + return this.maxHealth; + } + + @Override + public DataTracker getYaw() { + return this.yaw; + } + + @Override + public CollectionDataTracker getPassengers() { + return this.passengers; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/NameTagRendererImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/NameTagRendererImpl.java new file mode 100644 index 0000000..ef4d766 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/NameTagRendererImpl.java @@ -0,0 +1,277 @@ +package com.ticxo.modelengine.core.model.bone.render; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import org.bukkit.entity.Display.Billboard; +import org.joml.Vector3f; + +public class NameTagRendererImpl extends AbstractBehaviorRenderer implements NameTagRenderer { + private final Map spawnQueue = new HashMap<>(); + private final Map rendered = new HashMap<>(); + private final Map destroyQueue = new HashMap<>(); + private boolean initialized; + private BehaviorRendererParser cachedParser; + private RenderParsers cachedParserOwner; + + public NameTagRendererImpl(ActiveModel activeModel) { + super(activeModel); + } + + @Override + public void initialize() { + for (Entry boneEntry : this.activeModel.getBones().entrySet()) { + String boneId = boneEntry.getKey(); + ModelBone modelBone = boneEntry.getValue(); + this.create(boneId, modelBone); + } + + this.initialized = true; + } + + private void create(String boneId, ModelBone modelBone) { + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.NAMETAG); + if (!maybeData.isEmpty()) { + BoneBehavior nameTagData = (BoneBehavior)maybeData.get(); + NameTagRendererImpl.NameTagImpl nameTag = new NameTagRendererImpl.NameTagImpl( + this.nmsHandler.getEntityHandler().getNextEntityId(), UUID.randomUUID(), this.nmsHandler.getEntityHandler().getNextEntityId(), UUID.randomUUID() + ); + nameTag.position.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getLocation()); + nameTag.jsonString.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getJsonString()); + nameTag.visibility.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).isVisible()); + nameTag.backgroundColor + .set( + ((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).isUseDefaultBackgroundColor() + ? 1073741824 + : ((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getBackgroundColor() + ); + nameTag.billboard.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getBillboard()); + nameTag.textOpacity.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getTextOpacity()); + nameTag.lineWidth.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getLineWidth()); + nameTag.translate.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getPosition()); + nameTag.scale.set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getScale()); + nameTag.getStyle().set(this.getStyle((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData)); + nameTag.getBrightness().set(modelBone.getBrightness()); + this.spawnQueue.put(boneId, nameTag); + this.destroyQueue.remove(boneId); + } + } + + @Override + public void readBoneData() { + if (this.initialized) { + this.destroyQueue.putAll(this.rendered); + + for (Entry boneEntry : this.activeModel.getBones().entrySet()) { + String boneId = boneEntry.getKey(); + ModelBone modelBone = boneEntry.getValue(); + NameTagRenderer.NameTag renderer = this.getQueued(boneId); + if (renderer != null) { + this.read(boneId, renderer, modelBone); + } else { + this.create(boneId, modelBone); + } + } + } + } + + private void read(String boneId, NameTagRenderer.NameTag nameTag, ModelBone modelBone) { + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.NAMETAG); + maybeData.ifPresent( + nameTagData -> { + nameTag.getPosition().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getLocation()); + nameTag.getJsonString().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getJsonString()); + nameTag.getVisibility().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).isVisible()); + nameTag.getBillboard().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getBillboard()); + nameTag.getBackgroundColor() + .set( + ((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).isUseDefaultBackgroundColor() + ? 1073741824 + : ((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getBackgroundColor() + ); + nameTag.getTextOpacity().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getTextOpacity()); + nameTag.getLineWidth().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getLineWidth()); + nameTag.getTranslate().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getPosition()); + nameTag.getScale().set(((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData).getScale()); + nameTag.getStyle().set(this.getStyle((com.ticxo.modelengine.api.model.bone.type.NameTag)nameTagData)); + nameTag.getBrightness().set(modelBone.getBrightness()); + this.destroyQueue.remove(boneId); + } + ); + } + + private byte getStyle(com.ticxo.modelengine.api.model.bone.type.NameTag nameTagData) { + byte style = 0; + style = TMath.setBit(style, 0, nameTagData.isShadow()); + style = TMath.setBit(style, 1, nameTagData.isSeeThrough()); + style = TMath.setBit(style, 2, nameTagData.isUseDefaultBackgroundColor()); + + return switch (nameTagData.getAlignment()) { + case CENTER -> style; + case LEFT -> (byte)(style | 8); + case RIGHT -> (byte)(style | 16); + default -> throw new IncompatibleClassChangeError(); + }; + } + + @Override + public void sendToClient(RenderParsers parsers) { + if (this.initialized) { + this.destroyQueue.keySet().forEach(this.rendered::remove); + this.parser(parsers).sendToClients(this); + this.rendered.putAll(this.spawnQueue); + this.spawnQueue.clear(); + this.destroyQueue.clear(); + } + } + + @Override + public void destroy(RenderParsers parsers) { + if (this.initialized) { + parsers.getBehaviorParser(this).destroy(this); + } + } + + private BehaviorRendererParser parser(RenderParsers parsers) { + if (this.cachedParser == null || this.cachedParserOwner != parsers) { + this.cachedParserOwner = parsers; + this.cachedParser = parsers.getBehaviorParser(this); + } + + return this.cachedParser; + } + + @Override + public Map getSpawnQueue() { + return this.spawnQueue; + } + + @Override + public Map getRendered() { + return this.rendered; + } + + @Override + public Map getDestroyQueue() { + return this.destroyQueue; + } + + public static class NameTagImpl implements NameTagRenderer.NameTag { + private final int pivotId; + private final UUID pivotUuid; + private final int tagId; + private final UUID tagUuid; + private final DataTracker position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final DataTracker jsonString = new DataTracker<>(); + private final DataTracker visibility = new DataTracker<>(true); + private final DataTracker backgroundColor = new DataTracker<>(1073741824); + private final DataTracker billboard = new DataTracker<>(Billboard.CENTER); + private final DataTracker textOpacity = new DataTracker<>((byte)0); + private final DataTracker lineWidth = new DataTracker<>(0); + private final DataTracker translate = new DataTracker<>(new Vector3f(0.0F)); + private final DataTracker scale = new DataTracker<>(new Vector3f(1.0F)); + private final DataTracker style = new DataTracker<>((byte)0); + private final DataTracker brightness = new DataTracker<>(0); + private final PositionCodec positionCodec = new PositionCodec(); + + public NameTagImpl(int pivotId, UUID pivotUuid, int tagId, UUID tagUuid) { + this.pivotId = pivotId; + this.pivotUuid = pivotUuid; + this.tagId = tagId; + this.tagUuid = tagUuid; + } + + @Override + public int getPivotId() { + return this.pivotId; + } + + @Override + public UUID getPivotUuid() { + return this.pivotUuid; + } + + @Override + public int getTagId() { + return this.tagId; + } + + @Override + public UUID getTagUuid() { + return this.tagUuid; + } + + @Override + public DataTracker getPosition() { + return this.position; + } + + @Override + public DataTracker getJsonString() { + return this.jsonString; + } + + @Override + public DataTracker getVisibility() { + return this.visibility; + } + + @Override + public DataTracker getBackgroundColor() { + return this.backgroundColor; + } + + @Override + public DataTracker getBillboard() { + return this.billboard; + } + + @Override + public DataTracker getTextOpacity() { + return this.textOpacity; + } + + @Override + public DataTracker getLineWidth() { + return this.lineWidth; + } + + @Override + public DataTracker getTranslate() { + return this.translate; + } + + @Override + public DataTracker getScale() { + return this.scale; + } + + @Override + public DataTracker getStyle() { + return this.style; + } + + @Override + public DataTracker getBrightness() { + return this.brightness; + } + + @Override + public PositionCodec getPositionCodec() { + return this.positionCodec; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/SegmentRendererImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/SegmentRendererImpl.java new file mode 100644 index 0000000..78654bc --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/SegmentRendererImpl.java @@ -0,0 +1,361 @@ +package com.ticxo.modelengine.core.model.bone.render; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.BoneItems; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.type.HeldItem; +import com.ticxo.modelengine.api.model.bone.type.Segment; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker; +import com.ticxo.modelengine.api.utils.math.SafeTransform; +import com.ticxo.modelengine.core.model.render.DisplayBoneImpl; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class SegmentRendererImpl extends AbstractBehaviorRenderer implements SegmentRenderer { + private final EntityHandler entityHandler; + private final Map spawnQueue = new HashMap<>(); + private final Map rendered = new HashMap<>(); + private final Map destroyQueue = new HashMap<>(); + private boolean initialized; + private final Map unhandled = new HashMap<>(); + private final Map bones = new HashMap<>(); + private BehaviorRendererParser cachedParser; + private RenderParsers cachedParserOwner; + + public SegmentRendererImpl(ActiveModel activeModel) { + super(activeModel); + this.entityHandler = this.nmsHandler.getEntityHandler(); + } + + @Override + public void initialize() { + for (Entry entry : this.activeModel.getBones().entrySet()) { + this.createPivotOrBone(entry.getKey(), entry.getValue(), this.unhandled); + } + + for (Entry entry : this.unhandled.entrySet()) { + this.createBone(entry.getKey(), entry.getValue(), null); + } + + this.unhandled.clear(); + this.initialized = true; + } + + private void createPivotOrBone(String boneId, ModelBone modelBone, Map unhandled) { + if (!this.createPivot(boneId, modelBone)) { + this.createBone(boneId, modelBone, unhandled); + } + } + + private boolean createPivot(String boneId, ModelBone modelBone) { + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.SEGMENT); + if (maybeData.isEmpty()) { + return false; + } else { + BoneBehavior segmentData = (BoneBehavior)maybeData.get(); + SegmentRendererImpl.PivotImpl pivot = new SegmentRendererImpl.PivotImpl(this.entityHandler.getNextEntityId()); + pivot.getPosition().set(((Segment)segmentData).getWorldLocation()); + pivot.getYaw().set(-modelBone.getYaw() * (float) (Math.PI / 180.0)); + this.spawnQueue.put(boneId, pivot); + this.destroyQueue.remove(boneId); + return true; + } + } + + private void createBone(String boneId, ModelBone modelBone, @Nullable Map unhandled) { + if (modelBone.isRenderer() && modelBone.getPivot() != null) { + SegmentRendererImpl.PivotImpl pivot = this.getPivot(modelBone.getPivot().getUniqueBoneId()); + if (pivot == null) { + if (unhandled != null) { + unhandled.put(boneId, modelBone); + } + } else { + SafeTransform transform = modelBone.getGlobalTransform(); + BoneItems models = modelBone.getModels(); + SegmentRendererImpl.SegmentDisplayBoneImpl bone = new SegmentRendererImpl.SegmentDisplayBoneImpl(boneId, pivot); + bone.getGlowing().set(modelBone.isGlowing()); + bone.getGlowColor().set(modelBone.getGlowColor()); + bone.getBrightness().set(modelBone.getBrightness()); + bone.getBillboard().set(modelBone.getBillboard()); + bone.getVisibility().set(modelBone.isVisible()); + bone.getPosition().set(transform.getPosition().rotateY(pivot.yaw.get())); + bone.getLeftRotation().set(transform.getLeftQuaternion().rotateLocalY(pivot.yaw.get())); + bone.getScale().set(modelBone.isScaleHidden() ? new Vector3f() : transform.getScale()); + bone.getRightRotation().set(transform.getRightQuaternion()); + bone.getDisplay().set(ItemDisplayTransform.HEAD); + bone.getSnapshotHandler().recordSnapshot(); + models.forEach((uuid, stack) -> { + DisplayBoneImpl.BoneDataImpl data = new DisplayBoneImpl.BoneDataImpl(this.entityHandler.getNextEntityId(), bone); + data.getModel().set(stack.clone()); + bone.getModel().put(uuid, data); + pivot.passengers.add(data.getId()); + }); + this.initializeSpecialBehaviorRender(modelBone, bone); + this.bones.put(boneId, bone); + pivot.spawnQueue.put(boneId, bone); + pivot.destroyQueue.remove(boneId); + } + } + } + + private void initializeSpecialBehaviorRender(ModelBone modelBone, DisplayBone bone) { + modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM).ifPresent(item -> bone.getDisplay().set(((HeldItem)item).getDisplay())); + modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(limb -> bone.getDisplay().set(ItemDisplayTransform.THIRDPERSON_RIGHTHAND)); + } + + @Nullable + private SegmentRendererImpl.PivotImpl getPivot(String boneId) { + SegmentRenderer.Pivot pivot = this.getQueued(boneId); + return pivot instanceof SegmentRendererImpl.PivotImpl impl ? impl : null; + } + + @Override + public void readBoneData() { + if (this.initialized) { + this.destroyQueue.putAll(this.rendered); + ArrayList boneReadQueue = new ArrayList<>(); + ArrayList createQueue = new ArrayList<>(); + + for (Entry entry : this.activeModel.getBones().entrySet()) { + String boneId = entry.getKey(); + ModelBone modelBone = entry.getValue(); + SegmentRenderer.Pivot pivot = this.getQueued(boneId); + if (pivot != null) { + this.readPivotBone(boneId, pivot, modelBone); + } else { + SegmentRenderer.SegmentDisplayBone displayBone = this.bones.get(boneId); + if (displayBone != null) { + boneReadQueue.add(() -> this.readDisplayBone(boneId, displayBone, modelBone)); + } else { + createQueue.add(() -> this.createPivotOrBone(boneId, modelBone, this.unhandled)); + } + } + } + + boneReadQueue.forEach(Runnable::run); + createQueue.forEach(Runnable::run); + + for (Entry entryx : this.unhandled.entrySet()) { + this.createBone(entryx.getKey(), entryx.getValue(), null); + } + + this.unhandled.clear(); + this.spawnQueue + .forEach( + (pivotName, pivotx) -> pivotx.getDestroyQueue().forEach((s, bone) -> bone.getModel().keySet().forEach(id -> pivotx.getPassengers().remove(id))) + ); + this.rendered + .forEach( + (pivotName, pivotx) -> pivotx.getDestroyQueue().forEach((s, bone) -> bone.getModel().keySet().forEach(id -> pivotx.getPassengers().remove(id))) + ); + } + } + + private void readPivotBone(String boneId, SegmentRenderer.Pivot pivot, ModelBone modelBone) { + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.SEGMENT); + maybeData.ifPresent(segmentData -> { + pivot.getPosition().set(((Segment)segmentData).getWorldLocation()); + pivot.getYaw().set(-modelBone.getYaw() * (float) (Math.PI / 180.0)); + this.destroyQueue.remove(boneId); + }); + } + + private void readDisplayBone(String boneId, SegmentRenderer.SegmentDisplayBone bone, ModelBone modelBone) { + DataTracker shouldRender = bone.getRender(); + shouldRender.set(!modelBone.isEffectivelyInvisible()); + SegmentRenderer.Pivot pivot = bone.getPivot(); + if (shouldRender.get() || shouldRender.isDirty()) { + SafeTransform transform = modelBone.getGlobalTransform(); + bone.getStep().set(modelBone.pollModelScaleChanged() || modelBone.shouldStep() || shouldRender.isDirty()); + bone.getPosition().set(transform.getPosition().rotateY(pivot.getYaw().get())); + bone.getLeftRotation().set(transform.getLeftQuaternion().rotateLocalY(pivot.getYaw().get(), new Quaternionf())); + bone.getScale().set(modelBone.isScaleHidden() ? new Vector3f() : transform.getScale()); + bone.getRightRotation().set(transform.getRightQuaternion()); + bone.getBillboard().set(modelBone.getBillboard()); + if (!modelBone.isScaleHidden()) { + bone.getVisibility().set(modelBone.isVisible()); + } + + bone.getGlowing().set(modelBone.isGlowing()); + bone.getGlowColor().set(modelBone.getGlowColor()); + bone.getBrightness().set(modelBone.getBrightness()); + bone.getSnapshotHandler().recordSnapshot(); + BoneItems models = modelBone.getModels(); + if (models.isDirty()) { + models.clearDirty(); + ((SegmentRendererImpl.SegmentDisplayBoneImpl)bone).updateBoneData(this.entityHandler, pivot.getPassengers(), models); + } + + this.updateSpecialBehaviorRender(modelBone, bone); + } + + shouldRender.clearDirty(); + pivot.getDestroyQueue().remove(boneId); + } + + private void updateSpecialBehaviorRender(ModelBone modelBone, DisplayBone bone) { + modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM).ifPresent(item -> bone.getDisplay().set(((HeldItem)item).getDisplay())); + } + + @Override + public void sendToClient(RenderParsers parsers) { + if (this.initialized) { + this.destroyQueue.keySet().forEach(s -> { + SegmentRenderer.Pivot pivot = this.rendered.remove(s); + if (pivot != null) { + pivot.getSpawnQueue().forEach((s1, bone) -> this.bones.remove(s1)); + pivot.getRendered().forEach((s1, bone) -> this.bones.remove(s1)); + pivot.getDestroyQueue().forEach((s1, bone) -> this.bones.remove(s1)); + } + }); + this.parser(parsers).sendToClients(this); + this.rendered.putAll(this.spawnQueue); + this.spawnQueue.clear(); + this.destroyQueue.clear(); + this.rendered.forEach((s, pivot) -> { + pivot.getDestroyQueue().forEach((s1, bone) -> { + pivot.getRendered().remove(s1); + this.bones.remove(s1); + }); + pivot.getRendered().putAll(pivot.getSpawnQueue()); + pivot.getSpawnQueue().clear(); + }); + } + } + + @Override + public void destroy(RenderParsers parsers) { + if (this.initialized) { + parsers.getBehaviorParser(this).destroy(this); + } + } + + private BehaviorRendererParser parser(RenderParsers parsers) { + if (this.cachedParser == null || this.cachedParserOwner != parsers) { + this.cachedParserOwner = parsers; + this.cachedParser = parsers.getBehaviorParser(this); + } + + return this.cachedParser; + } + + @Override + public Map getSpawnQueue() { + return this.spawnQueue; + } + + @Override + public Map getRendered() { + return this.rendered; + } + + @Override + public Map getDestroyQueue() { + return this.destroyQueue; + } + + public static class PivotImpl implements SegmentRenderer.Pivot { + private final Map spawnQueue = new HashMap<>(); + private final Map rendered = new HashMap<>(); + private final Map destroyQueue = new HashMap<>(); + private final int id; + private final UUID uuid = UUID.randomUUID(); + private final DataTracker position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final PositionCodec positionCodec = new PositionCodec(); + private final DataTracker yaw = new DataTracker<>(); + private final CollectionDataTracker passengers = new CollectionDataTracker<>(new HashSet<>()); + + @Override + public void clearDirty() { + this.yaw.clearDirty(); + this.passengers.clearDirty(); + } + + @Override + public int getId() { + return this.id; + } + + @Override + public UUID getUuid() { + return this.uuid; + } + + @Override + public DataTracker getPosition() { + return this.position; + } + + @Override + public PositionCodec getPositionCodec() { + return this.positionCodec; + } + + @Override + public DataTracker getYaw() { + return this.yaw; + } + + @Override + public CollectionDataTracker getPassengers() { + return this.passengers; + } + + public PivotImpl(int id) { + this.id = id; + } + + @Override + public Map getSpawnQueue() { + return this.spawnQueue; + } + + @Override + public Map getRendered() { + return this.rendered; + } + + @Override + public Map getDestroyQueue() { + return this.destroyQueue; + } + } + + public static class SegmentDisplayBoneImpl extends DisplayBoneImpl implements SegmentRenderer.SegmentDisplayBone { + private final SegmentRenderer.Pivot pivot; + + public SegmentDisplayBoneImpl(String boneId, SegmentRenderer.Pivot pivot) { + super(boneId); + this.pivot = pivot; + } + + @Override + protected void updateBoneData(EntityHandler entityHandler, CollectionDataTracker passengerCollector, BoneItems boneItems) { + super.updateBoneData(entityHandler, passengerCollector, boneItems); + } + + @Override + public SegmentRenderer.Pivot getPivot() { + return this.pivot; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/SubHitboxRendererImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/SubHitboxRendererImpl.java new file mode 100644 index 0000000..17a751b --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/bone/render/SubHitboxRendererImpl.java @@ -0,0 +1,190 @@ +package com.ticxo.modelengine.core.model.bone.render; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import org.joml.Vector3f; + +public class SubHitboxRendererImpl extends AbstractBehaviorRenderer implements SubHitboxRenderer { + private final Map spawnQueue = new HashMap<>(); + private final Map rendered = new HashMap<>(); + private final Map destroyQueue = new HashMap<>(); + private boolean initialized; + private BehaviorRendererParser cachedParser; + private RenderParsers cachedParserOwner; + + public SubHitboxRendererImpl(ActiveModel activeModel) { + super(activeModel); + } + + @Override + public void initialize() { + for (Entry boneEntry : this.activeModel.getBones().entrySet()) { + String boneId = boneEntry.getKey(); + ModelBone modelBone = boneEntry.getValue(); + this.create(boneId, modelBone); + } + + this.initialized = true; + } + + private void create(String boneId, ModelBone modelBone) { + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.SUB_HITBOX); + if (!maybeData.isEmpty()) { + BoneBehavior subHitboxData = (BoneBehavior)maybeData.get(); + if (!((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).isOBB()) { + SubHitboxRendererImpl.SubHitboxImpl subHitbox = new SubHitboxRendererImpl.SubHitboxImpl( + this.nmsHandler.getEntityHandler().getNextEntityId(), + ((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getHitboxId(), + UUID.randomUUID(), + UUID.randomUUID() + ); + subHitbox.position.set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getLocation()); + subHitbox.width.set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getDimension().x); + subHitbox.height.set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getDimension().y); + this.spawnQueue.put(boneId, subHitbox); + this.destroyQueue.remove(boneId); + } + } + } + + @Override + public void readBoneData() { + if (this.initialized) { + this.destroyQueue.putAll(this.rendered); + + for (Entry boneEntry : this.activeModel.getBones().entrySet()) { + String boneId = boneEntry.getKey(); + ModelBone modelBone = boneEntry.getValue(); + SubHitboxRenderer.SubHitbox renderer = this.getQueued(boneId); + if (renderer != null) { + this.read(boneId, renderer, modelBone); + } else { + this.create(boneId, modelBone); + } + } + } + } + + private void read(String boneId, SubHitboxRenderer.SubHitbox subHitbox, ModelBone modelBone) { + Optional maybeData = modelBone.getBoneBehavior(BoneBehaviorTypes.SUB_HITBOX); + maybeData.ifPresent(subHitboxData -> { + subHitbox.getPosition().set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getLocation()); + subHitbox.getWidth().set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getDimension().x); + subHitbox.getHeight().set(((com.ticxo.modelengine.api.model.bone.type.SubHitbox)subHitboxData).getDimension().y); + this.destroyQueue.remove(boneId); + }); + } + + @Override + public void sendToClient(RenderParsers parsers) { + if (this.initialized) { + this.destroyQueue.keySet().forEach(this.rendered::remove); + this.parser(parsers).sendToClients(this); + this.rendered.putAll(this.spawnQueue); + this.spawnQueue.clear(); + this.destroyQueue.clear(); + } + } + + @Override + public void destroy(RenderParsers parsers) { + if (this.initialized) { + parsers.getBehaviorParser(this).destroy(this); + } + } + + private BehaviorRendererParser parser(RenderParsers parsers) { + if (this.cachedParser == null || this.cachedParserOwner != parsers) { + this.cachedParserOwner = parsers; + this.cachedParser = parsers.getBehaviorParser(this); + } + + return this.cachedParser; + } + + @Override + public Map getSpawnQueue() { + return this.spawnQueue; + } + + @Override + public Map getRendered() { + return this.rendered; + } + + @Override + public Map getDestroyQueue() { + return this.destroyQueue; + } + + public static class SubHitboxImpl implements SubHitboxRenderer.SubHitbox { + private final int pivotId; + private final int hitboxId; + private final UUID pivotUuid; + private final UUID hitboxUuid; + private final DataTracker position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final DataTracker width = new DataTracker<>(); + private final DataTracker height = new DataTracker<>(); + private final PositionCodec positionCodec = new PositionCodec(); + + public SubHitboxImpl(int pivotId, int hitboxId, UUID pivotUuid, UUID hitboxUuid) { + this.pivotId = pivotId; + this.hitboxId = hitboxId; + this.pivotUuid = pivotUuid; + this.hitboxUuid = hitboxUuid; + } + + @Override + public int getPivotId() { + return this.pivotId; + } + + @Override + public int getHitboxId() { + return this.hitboxId; + } + + @Override + public UUID getPivotUuid() { + return this.pivotUuid; + } + + @Override + public UUID getHitboxUuid() { + return this.hitboxUuid; + } + + @Override + public DataTracker getPosition() { + return this.position; + } + + @Override + public DataTracker getWidth() { + return this.width; + } + + @Override + public DataTracker getHeight() { + return this.height; + } + + @Override + public PositionCodec getPositionCodec() { + return this.positionCodec; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayBoneImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayBoneImpl.java new file mode 100644 index 0000000..8f72b85 --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayBoneImpl.java @@ -0,0 +1,242 @@ +package com.ticxo.modelengine.core.model.render; + +import com.ticxo.modelengine.api.lod.BoneSnapshotHandler; +import com.ticxo.modelengine.api.model.bone.BoneItems; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.QuaternionfDataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.Vector3fDataTracker; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntIterator; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSet; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import org.bukkit.entity.Display.Billboard; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.bukkit.inventory.ItemStack; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayBoneImpl implements DisplayBone { + private final String boneId; + private final BoneSnapshotHandler snapshotHandler = new BoneSnapshotHandler(this); + private final DataTracker render = new DataTracker<>(true); + private final DataTracker step = new DataTracker<>(false); + private final DataTracker position = new Vector3fDataTracker(); + private final DataTracker leftRotation = new QuaternionfDataTracker(); + private final DataTracker scale = new Vector3fDataTracker(); + private final DataTracker rightRotation = new QuaternionfDataTracker(); + private final DataTracker billboard = new DataTracker<>(Billboard.FIXED); + private final DataTracker display = new DataTracker<>(ItemDisplayTransform.NONE); + private final DataTracker visibility = new DataTracker<>(true); + private final DataTracker glowing = new DataTracker<>(false); + private final DataTracker glowColor = new DataTracker<>(-1); + private final DataTracker brightness = new DataTracker<>(-1); + private final DataTracker> glowAudience = new DataTracker<>(); + private final DataTracker audienceGlowing = new DataTracker<>(false); + private final DataTracker audienceGlowColor = new DataTracker<>(-1); + private final Int2ObjectMap model = new Int2ObjectOpenHashMap(); + private final UpdateScheme modelUpdateScheme = new UpdateScheme<>(); + + protected void updateBoneData(EntityHandler entityHandler, CollectionDataTracker passengerCollector, BoneItems boneItems) { + Map newItems = boneItems.getItems(); + IntSet oldKeys = this.model.keySet(); + IntOpenHashSet added = new IntOpenHashSet(newItems.keySet()); + IntOpenHashSet removed = new IntOpenHashSet(oldKeys); + removed.removeAll(added); + added.removeAll(oldKeys); + HashSet reusableData = new HashSet<>(); + IntIterator it = removed.iterator(); + + while (it.hasNext()) { + reusableData.add((DisplayBone.BoneData)this.model.remove(it.nextInt())); + } + + Iterator iterator = reusableData.iterator(); + IntIterator itx = added.iterator(); + + while (itx.hasNext()) { + int hash = itx.nextInt(); + ItemStack stack = newItems.get(hash).clone(); + if (iterator.hasNext()) { + DisplayBone.BoneData data = iterator.next(); + int oldHash = data.getModelHash(); + data.getModel().set(stack); + this.modelUpdateScheme.addUpdated(data); + this.model.remove(oldHash); + this.model.put(hash, data); + } else { + DisplayBoneImpl.BoneDataImpl data = new DisplayBoneImpl.BoneDataImpl(entityHandler.getNextEntityId(), this); + data.getModel().set(stack); + this.model.put(hash, data); + this.modelUpdateScheme.addAdded(data); + passengerCollector.add(data.getId()); + } + } + + while (iterator.hasNext()) { + DisplayBone.BoneData data = iterator.next(); + this.modelUpdateScheme.addRemove(data); + passengerCollector.remove(data.getId()); + } + } + + @Override + public String getBoneId() { + return this.boneId; + } + + @Override + public BoneSnapshotHandler getSnapshotHandler() { + return this.snapshotHandler; + } + + @Override + public DataTracker getRender() { + return this.render; + } + + @Override + public DataTracker getStep() { + return this.step; + } + + @Override + public DataTracker getPosition() { + return this.position; + } + + @Override + public DataTracker getLeftRotation() { + return this.leftRotation; + } + + @Override + public DataTracker getScale() { + return this.scale; + } + + @Override + public DataTracker getRightRotation() { + return this.rightRotation; + } + + @Override + public DataTracker getBillboard() { + return this.billboard; + } + + @Override + public DataTracker getDisplay() { + return this.display; + } + + @Override + public DataTracker getVisibility() { + return this.visibility; + } + + @Override + public DataTracker getGlowing() { + return this.glowing; + } + + @Override + public DataTracker getGlowColor() { + return this.glowColor; + } + + @Override + public DataTracker getBrightness() { + return this.brightness; + } + + @Override + public DataTracker> getGlowAudience() { + return this.glowAudience; + } + + @Override + public DataTracker getAudienceGlowing() { + return this.audienceGlowing; + } + + @Override + public DataTracker getAudienceGlowColor() { + return this.audienceGlowColor; + } + + public Int2ObjectMap getModel() { + return this.model; + } + + @Override + public UpdateScheme getModelUpdateScheme() { + return this.modelUpdateScheme; + } + + public DisplayBoneImpl(String boneId) { + this.boneId = boneId; + } + + public static class BoneDataImpl implements DisplayBone.BoneData { + private final int id; + private final UUID uuid = UUID.randomUUID(); + private final DisplayBone bone; + private final DataTracker model = new DataTracker<>(); + + @Override + public boolean equals(Object object) { + if (object != null && this.getClass() == object.getClass()) { + DisplayBoneImpl.BoneDataImpl boneData = (DisplayBoneImpl.BoneDataImpl)object; + return Objects.equals(this.model, boneData.model); + } else { + return false; + } + } + + @Override + public int hashCode() { + return Objects.hashCode(this.model); + } + + @Override + public int getModelHash() { + return this.model.get().hashCode(); + } + + @Override + public int getId() { + return this.id; + } + + @Override + public UUID getUuid() { + return this.uuid; + } + + @Override + public DisplayBone getBone() { + return this.bone; + } + + @Override + public DataTracker getModel() { + return this.model; + } + + public BoneDataImpl(int id, DisplayBone bone) { + this.id = id; + this.bone = bone; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayFireImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayFireImpl.java new file mode 100644 index 0000000..f023c1d --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayFireImpl.java @@ -0,0 +1,60 @@ +package com.ticxo.modelengine.core.model.render; + +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker; +import java.util.UUID; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.joml.Vector3f; + +public class DisplayFireImpl implements DisplayFire { + private final int id; + private final UUID uuid = UUID.randomUUID(); + private final DataTracker position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set, Vector3f::new); + private final DataTracker scale = new UpdateDataTracker<>(new Vector3f(), Vector3f::set, Vector3f::new); + private final DataTracker fireModel = new DataTracker<>(new ItemStack(Material.AIR), ItemStack::isSimilar); + private final DataTracker visible = new DataTracker<>(false); + + @Override + public void clearDirty() { + this.position.clearDirty(); + this.scale.clearDirty(); + this.fireModel.clearDirty(); + this.visible.clearDirty(); + } + + @Override + public int getId() { + return this.id; + } + + @Override + public UUID getUuid() { + return this.uuid; + } + + @Override + public DataTracker getPosition() { + return this.position; + } + + @Override + public DataTracker getScale() { + return this.scale; + } + + @Override + public DataTracker getFireModel() { + return this.fireModel; + } + + @Override + public DataTracker getVisible() { + return this.visible; + } + + public DisplayFireImpl(int id) { + this.id = id; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayRendererImpl.java b/core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayRendererImpl.java new file mode 100644 index 0000000..b3a074f --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/model/render/DisplayRendererImpl.java @@ -0,0 +1,796 @@ +package com.ticxo.modelengine.core.model.render; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BoneTransformReadEvent; +import com.ticxo.modelengine.api.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.BoneItems; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.model.bone.type.HeldItem; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker; +import com.ticxo.modelengine.api.utils.math.SafeTransform; +import com.ticxo.modelengine.api.utils.math.TMath; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Queue; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.ItemDisplay; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Transformation; +import org.joml.Quaternionf; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class DisplayRendererImpl implements DisplayRenderer { + private final ActiveModel activeModel; + private final EntityHandler entityHandler; + private final Map spawnQueue = new HashMap<>(); + private final Map rendered = new HashMap<>(); + private final Map destroyQueue = new HashMap<>(); + private final Set fullUpdate = new HashSet<>(); + private final AtomicInteger glowAudienceBones = new AtomicInteger(); + private final Vector3f scratchPosition = new Vector3f(); + private final Vector3f scratchScale = new Vector3f(); + private final Quaternionf scratchLeft = new Quaternionf(); + private final Quaternionf scratchRight = new Quaternionf(); + private final Quaternionf scratchRotated = new Quaternionf(); + private boolean trigValid; + private int trigYawBits; + private float yawSin; + private float yawCos; + private float halfYawSin; + private float halfYawCos; + private DisplayRendererImpl.PivotImpl pivot; + private DisplayRendererImpl.HitboxImpl hitbox; + private boolean initialized; + private boolean firstSpawned; + private final Queue queuedTasks = new ConcurrentLinkedQueue<>(); + private ModelRendererParser cachedParser; + private RenderParsers cachedParserOwner; + + public DisplayRendererImpl(ActiveModel activeModel) { + this.activeModel = activeModel; + this.entityHandler = ModelEngineAPI.getEntityHandler(); + } + + @Override + public void updatePivotOverride(PivotOverride override) { + if (this.initialized) { + this.updatePivotOverride0(override); + } else { + this.queuedTasks.add(() -> this.updatePivotOverride0(override)); + } + } + + private void updatePivotOverride0(PivotOverride override) { + this.activeModel.getPivotOverride().ifPresent(old -> old.removePassenger(this.pivot.id)); + if (override != null) { + override.addPassenger(this.pivot.id); + } + } + + @Override + public void initialize() { + ModeledEntity model = this.activeModel.getModeledEntity(); + BaseEntity base = model.getBase(); + Location location = base.getLocation(); + ModelBlueprint blueprint = this.activeModel.getBlueprint(); + Vector3fc scale = this.activeModel.getScale(); + Vector3fc hitboxScale = this.activeModel.getHitboxScale(); + com.ticxo.modelengine.api.entity.Hitbox mainHitbox = blueprint.getMainHitbox(); + float scaledEyeHeight = (float)mainHitbox.getEyeHeight() * scale.y(); + float scaledHeight = (float)mainHitbox.getHeight() * hitboxScale.y(); + float scaledWidth = (float)mainHitbox.getMaxWidth() * hitboxScale.x(); + this.pivot = new DisplayRendererImpl.PivotImpl(this.entityHandler.getNextEntityId()); + this.pivot.pivotOverride = this.activeModel.getPivotOverride().orElse(null); + this.updateCameraPivot(); + this.pivot.updatePosition(location, scaledEyeHeight); + this.pivot.getYaw().set(this.pivot.cameraEye != null ? 0.0F : -this.activeModel.getYBodyRot() * (float) (Math.PI / 180.0)); + Vector3f initialOffset = this.pivot.getMountOffset(scaledEyeHeight); + + for (Entry entry : this.activeModel.getBones().entrySet()) { + this.create(entry.getKey(), entry.getValue(), initialOffset); + } + + this.forBehaviorRenderer(behaviorRenderer -> { + behaviorRenderer.setModelRenderer(this); + behaviorRenderer.initialize(); + }); + this.hitbox = new DisplayRendererImpl.HitboxImpl( + this.entityHandler.getNextEntityId(), this.entityHandler.getNextEntityId(), this.entityHandler.getNextEntityId() + ); + this.hitbox.updatePosition(location); + this.hitbox.getHeight().set(scaledHeight); + this.hitbox.getWidth().set(scaledWidth); + this.hitbox.getShadowRadius().set(blueprint.getShadowRadius() * scale.x()); + this.hitbox.getHitboxVisible().set(this.activeModel.isHitboxVisible()); + this.hitbox.getShadowVisible().set(this.activeModel.isShadowVisible()); + this.hitbox.getFireVisible().set(this.activeModel.canRenderFire()); + if (this.hitbox.isHitboxDirty() || this.hitbox.getFireVisible().isDirty()) { + this.hitbox.updateFireDisplay(); + } + + this.hitbox.setOnFire(this.activeModel.isOnFire()); + ModelEngineAPI.getInteractionTracker().setModelRelay(this.hitbox.hitboxId, this.activeModel); + this.initialized = true; + this.firstSpawned = true; + + while (!this.queuedTasks.isEmpty()) { + this.queuedTasks.poll().run(); + } + } + + private void updateCameraPivot() { + Float eye = null; + Float height = null; + if (this.activeModel.isCameraPivot() + && this.pivot.pivotOverride != null + && this.activeModel.getModeledEntity().getBase().getOriginal() instanceof Entity entity) { + eye = this.entityHandler.getCameraEyeHeight(entity); + height = this.entityHandler.getCameraPivotHeight(entity); + if (eye == null || height == null) { + eye = null; + height = null; + } + } + + this.pivot.cameraEye = eye; + if (height != null || this.pivot.cameraHeight.get() != null) { + this.pivot.cameraHeight.set(height); + } + } + + private void create(String boneId, ModelBone modelBone, Vector3f offset) { + if (modelBone.isRenderer() && modelBone.getPivot() == null) { + BoneItems models = modelBone.getModels(); + DisplayBoneImpl bone = new DisplayBoneImpl(boneId); + this.applyGlow(bone, modelBone); + bone.getBrightness().set(modelBone.getBrightness()); + bone.getBillboard().set(modelBone.getBillboard()); + bone.getVisibility().set(modelBone.isVisible()); + SafeTransform transform = modelBone.getGlobalTransform(); + BoneTransformReadEvent event = new BoneTransformReadEvent( + modelBone, transform.getPosition(), transform.getLeftQuaternion(), transform.getScale(), transform.getRightQuaternion() + ); + Bukkit.getPluginManager().callEvent(event); + modelBone.forBehaviors(boneBehavior -> boneBehavior.modifyTransform(event)); + bone.getPosition().set(event.getPosition().rotateY(this.pivot.yaw.get()).sub(offset)); + bone.getLeftRotation().set(event.getLeftRotation().rotateLocalY(this.pivot.yaw.get())); + bone.getScale().set(modelBone.isScaleHidden() ? new Vector3f() : TMath.zerofyScale(event.getScale())); + bone.getRightRotation().set(event.getRightRotation()); + bone.getDisplay().set(ItemDisplayTransform.HEAD); + bone.getSnapshotHandler().recordSnapshot(); + models.forEach((uuid, stack) -> { + DisplayBoneImpl.BoneDataImpl data = new DisplayBoneImpl.BoneDataImpl(this.entityHandler.getNextEntityId(), bone); + data.getModel().set(stack.clone()); + bone.getModel().put(uuid, data); + this.pivot.passengers.add(data.getId()); + }); + this.initializeSpecialBehaviorRender(modelBone, bone); + this.spawnQueue.put(boneId, bone); + this.destroyQueue.remove(boneId); + } + } + + private void initializeSpecialBehaviorRender(ModelBone modelBone, DisplayBone bone) { + modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM).ifPresent(item -> bone.getDisplay().set(((HeldItem)item).getDisplay())); + modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(limb -> bone.getDisplay().set(ItemDisplayTransform.THIRDPERSON_RIGHTHAND)); + } + + @Override + public void readModelData() { + if (this.initialized) { + ModeledEntity model = this.activeModel.getModeledEntity(); + BaseEntity base = model.getBase(); + Location location = base.getLocation(); + ModelBlueprint blueprint = this.activeModel.getBlueprint(); + Vector3fc scale = this.activeModel.getScale(); + Vector3fc hitboxScale = this.activeModel.getHitboxScale(); + com.ticxo.modelengine.api.entity.Hitbox mainHitbox = blueprint.getMainHitbox(); + float scaledEyeHeight = (float)mainHitbox.getEyeHeight() * scale.y(); + float scaledHeight = (float)mainHitbox.getHeight() * hitboxScale.y(); + float scaledWidth = (float)mainHitbox.getMaxWidth() * hitboxScale.x(); + this.pivot.pivotOverride = this.activeModel.getPivotOverride().orElse(null); + this.updateCameraPivot(); + this.pivot.updatePosition(location, scaledEyeHeight); + this.pivot.getYaw().set(this.pivot.cameraEye != null ? 0.0F : -this.activeModel.getYBodyRot() * (float) (Math.PI / 180.0)); + Vector3f offset = this.pivot.getMountOffset(scaledEyeHeight); + boolean hasTransformListeners = BoneTransformReadEvent.getHandlerList().getRegisteredListeners().length > 0; + Map bones = this.activeModel.getBones(); + + for (Entry entry : bones.entrySet()) { + DisplayBone bone = this.getQueued(entry.getKey()); + if (bone == null) { + this.create(entry.getKey(), entry.getValue(), offset); + } else { + this.read(entry.getKey(), bone, entry.getValue(), offset, hasTransformListeners); + } + } + + for (Entry entryx : this.rendered.entrySet()) { + if (!bones.containsKey(entryx.getKey()) && !this.spawnQueue.containsKey(entryx.getKey())) { + this.destroyQueue.put(entryx.getKey(), entryx.getValue()); + } + } + + for (DisplayBone bone : this.destroyQueue.values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + this.pivot.passengers.remove(boneData.getId()); + } + } + + this.forBehaviorRenderer(BehaviorRenderer::readBoneData); + this.hitbox.updatePosition(location); + this.hitbox.getHeight().set(scaledHeight); + this.hitbox.getWidth().set(scaledWidth); + this.hitbox.getShadowRadius().set(blueprint.getShadowRadius() * scale.x()); + this.hitbox.getHitboxVisible().set(this.activeModel.isHitboxVisible()); + this.hitbox.getShadowVisible().set(this.activeModel.isShadowVisible()); + this.hitbox.getFireVisible().set(this.activeModel.canRenderFire()); + if (this.hitbox.isHitboxDirty() || this.hitbox.getFireVisible().isDirty()) { + this.hitbox.updateFireDisplay(); + } + + this.hitbox.setOnFire(this.activeModel.isOnFire()); + } + } + + private void read(String boneId, DisplayBone bone, ModelBone modelBone, Vector3f offset, boolean hasTransformListeners) { + DataTracker shouldRender = bone.getRender(); + shouldRender.set(!modelBone.isEffectivelyInvisible()); + if (shouldRender.get() || shouldRender.isDirty()) { + bone.getStep().set(modelBone.pollModelScaleChanged() || modelBone.shouldStep() || shouldRender.isDirty()); + SafeTransform transform = modelBone.getGlobalTransform(); + float yaw = this.pivot.yaw.get(); + int yawBits = Float.floatToRawIntBits(yaw); + if (!this.trigValid || yawBits != this.trigYawBits) { + this.trigYawBits = yawBits; + this.trigValid = true; + this.yawSin = org.joml.Math.sin(yaw); + this.yawCos = org.joml.Math.cosFromSin(this.yawSin, yaw); + float halfYaw = yaw * 0.5F; + this.halfYawSin = org.joml.Math.sin(halfYaw); + this.halfYawCos = org.joml.Math.cosFromSin(this.halfYawSin, halfYaw); + } + + if (!hasTransformListeners && !modelBone.hasBoneBehaviors()) { + bone.getPosition().set(rotateY(transform.getPosition(this.scratchPosition), this.yawSin, this.yawCos).sub(offset)); + bone.getLeftRotation().set(rotateLocalY(transform.getLeftQuaternion(this.scratchLeft), this.halfYawSin, this.halfYawCos, this.scratchRotated)); + bone.getScale().set(TMath.zerofyScale(transform.getScale(this.scratchScale), this.scratchScale)); + bone.getRightRotation().set(transform.getRightQuaternion(this.scratchRight)); + } else { + BoneTransformReadEvent event = new BoneTransformReadEvent( + modelBone, transform.getPosition(), transform.getLeftQuaternion(), transform.getScale(), transform.getRightQuaternion() + ); + if (hasTransformListeners) { + Bukkit.getPluginManager().callEvent(event); + } + + modelBone.forBehaviors(boneBehavior -> boneBehavior.modifyTransform(event)); + bone.getPosition().set(rotateY(event.getPosition(), this.yawSin, this.yawCos).sub(offset)); + bone.getLeftRotation().set(rotateLocalY(event.getLeftRotation(), this.halfYawSin, this.halfYawCos, this.scratchRotated)); + bone.getScale().set(TMath.zerofyScale(event.getScale())); + bone.getRightRotation().set(event.getRightRotation()); + } + + if (modelBone.isScaleHidden()) { + bone.getScale().set(this.scratchScale.zero()); + } + + bone.getBillboard().set(modelBone.getBillboard()); + if (!modelBone.isScaleHidden()) { + bone.getVisibility().set(modelBone.isVisible()); + } + + this.applyGlow(bone, modelBone); + bone.getBrightness().set(modelBone.getBrightness()); + bone.getSnapshotHandler().recordSnapshot(); + BoneItems models = modelBone.getModels(); + if (models.isDirty()) { + models.clearDirty(); + ((DisplayBoneImpl)bone).updateBoneData(this.entityHandler, this.pivot.getPassengers(), models); + } + + this.updateSpecialBehaviorRender(modelBone, bone); + } + + shouldRender.clearDirty(); + } + + private static Vector3f rotateY(Vector3f vector, float sin, float cos) { + float x = vector.x * cos + vector.z * sin; + float z = -vector.x * sin + vector.z * cos; + vector.x = x; + vector.z = z; + return vector; + } + + private static Quaternionf rotateLocalY(Quaternionf quaternion, float sin, float cos, Quaternionf dest) { + return dest.set( + cos * quaternion.x + sin * quaternion.z, + cos * quaternion.y + sin * quaternion.w, + cos * quaternion.z - sin * quaternion.x, + cos * quaternion.w - sin * quaternion.y + ); + } + + private void updateSpecialBehaviorRender(ModelBone modelBone, DisplayBone bone) { + modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM).ifPresent(item -> bone.getDisplay().set(((HeldItem)item).getDisplay())); + } + + private void applyGlow(DisplayBone bone, ModelBone modelBone) { + Set audience = modelBone.getGlowAudience(); + DataTracker> audienceTracker = bone.getGlowAudience(); + Set previousAudience = audienceTracker.get(); + if (!Objects.equals(previousAudience, audience)) { + if (previousAudience == null) { + this.glowAudienceBones.incrementAndGet(); + } else if (audience == null) { + this.glowAudienceBones.decrementAndGet(); + } + + audienceTracker.set(audience); + } + + if (audience == null) { + bone.getGlowing().set(modelBone.isGlowing()); + bone.getGlowColor().set(modelBone.getGlowColor()); + bone.getAudienceGlowing().set(false); + } else { + bone.getGlowing().set(false); + bone.getAudienceGlowing().set(modelBone.isGlowing()); + bone.getAudienceGlowColor().set(modelBone.getGlowColor()); + } + } + + @Override + public void sendToClient(RenderParsers parsers) { + if (this.initialized) { + this.forManagers(BehaviorManager::preBoneRender); + this.forBehavior(BoneBehavior::preRender); + + for (String boneId : this.destroyQueue.keySet()) { + DisplayBone removed = this.rendered.remove(boneId); + if (removed != null && removed.getGlowAudience().get() != null) { + this.glowAudienceBones.decrementAndGet(); + } + } + + this.activeModel.getPreSendCallback().invoker().run(); + this.parser(parsers).sendToClients(this); + this.activeModel.getPostSendCallback().invoker().run(); + this.rendered.putAll(this.spawnQueue); + this.spawnQueue.clear(); + this.destroyQueue.clear(); + this.forBehaviorRenderer(behaviorRenderer -> behaviorRenderer.sendToClient(parsers)); + this.forBehavior(BoneBehavior::onRender); + this.forBehavior(BoneBehavior::postRender); + this.forManagers(BehaviorManager::postBoneRender); + } + } + + @Override + public void destroy(RenderParsers parsers) { + if (this.initialized) { + this.forBehaviorRenderer(behaviorRenderer -> behaviorRenderer.destroy(parsers)); + parsers.getModelParser(this).destroy(this); + ModelEngineAPI.getInteractionTracker().removeModelRelay(this.hitbox.hitboxId); + this.activeModel.getPivotOverride().ifPresent(override -> { + ModeledEntity model = this.activeModel.getModeledEntity(); + if (model != null) { + List basePassengers = model.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + snapshot[i++] = passenger.getEntityId(); + } + + override.setBasePassengerSnapshot(snapshot); + } + + override.removePassenger(this.pivot.id); + }); + } + } + + @Override + public void createRealEntities() { + World world = this.activeModel.getModeledEntity().getBase().getLocation().getWorld(); + if (world != null) { + Vector3f pos = this.pivot.getPosition().get(); + Location location = new Location(world, pos.x, pos.y, pos.z); + + for (DisplayBone bone : this.rendered.values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + world.spawn(location, ItemDisplay.class, itemDisplay -> { + Quaternionf rotation = bone.getLeftRotation().get(); + if (ServerInfo.VERSION_NUMBER <= 19) { + rotation = rotation.rotateY((float) Math.PI, new Quaternionf()); + } + + itemDisplay.setTransformation(new Transformation(bone.getPosition().get(), rotation, bone.getScale().get(), new Quaternionf())); + itemDisplay.setItemStack(boneData.getModel().get().clone()); + itemDisplay.setItemDisplayTransform(bone.getDisplay().get()); + }); + } + } + } + } + + @Override + public boolean pollFirstSpawn() { + if (!this.firstSpawned) { + return false; + } else { + this.firstSpawned = false; + return true; + } + } + + @Override + public boolean hasGlowAudience() { + return this.glowAudienceBones.get() > 0; + } + + private void forManagers(Consumer> consumer) { + for (BehaviorManager manager : this.activeModel.getBehaviorManagers().values()) { + consumer.accept(manager); + } + } + + private void forBehavior(Consumer consumer) { + Map bones = this.activeModel.getBones(); + + for (String boneId : this.activeModel.getBlueprint().getBones().keySet()) { + ModelBone bone = bones.get(boneId); + if (bone != null) { + bone.forBehaviors(consumer); + } + } + } + + private void forBehaviorRenderer(Consumer consumer) { + for (BehaviorRenderer renderer : this.activeModel.getBehaviorRenderers().values()) { + if (!(renderer instanceof HeldItemRenderer)) { + consumer.accept(renderer); + } + } + } + + @Override + public int getTick() { + return this.activeModel.getModeledEntity().getTick(); + } + + @Override + public void pushFullUpdate(UUID uuid) { + this.fullUpdate.add(uuid); + } + + @Override + public boolean pollFullUpdate(UUID uuid) { + return this.fullUpdate.remove(uuid); + } + + private ModelRendererParser parser(RenderParsers parsers) { + if (this.cachedParser == null || this.cachedParserOwner != parsers) { + this.cachedParserOwner = parsers; + this.cachedParser = parsers.getModelParser(this); + } + + return this.cachedParser; + } + + @Override + public ActiveModel getActiveModel() { + return this.activeModel; + } + + @Override + public Map getSpawnQueue() { + return this.spawnQueue; + } + + @Override + public Map getRendered() { + return this.rendered; + } + + @Override + public Map getDestroyQueue() { + return this.destroyQueue; + } + + public DisplayRendererImpl.PivotImpl getPivot() { + return this.pivot; + } + + public DisplayRendererImpl.HitboxImpl getHitbox() { + return this.hitbox; + } + + @Override + public boolean isInitialized() { + return this.initialized; + } + + public class HitboxImpl implements DisplayRenderer.Hitbox { + private final int pivotId; + private final UUID pivotUuid = UUID.randomUUID(); + private final int hitboxId; + private final UUID hitboxUuid = UUID.randomUUID(); + private final int shadowId; + private final UUID shadowUuid = UUID.randomUUID(); + private final DataTracker position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final PositionCodec positionCodec = new PositionCodec(); + private final DataTracker width = new DataTracker<>(); + private final DataTracker height = new DataTracker<>(); + private final DataTracker shadowRadius = new DataTracker<>(); + private final DataTracker hitboxVisible = new DataTracker<>(); + private final DataTracker shadowVisible = new DataTracker<>(); + private final DataTracker fireVisible = new DataTracker<>(); + private final DataTracker onFire = new DataTracker<>(); + private final PooledCollection fireDisplay = new PooledCollection<>( + () -> new DisplayFireImpl(DisplayRendererImpl.this.entityHandler.getNextEntityId()) + ); + + public void updatePosition(Location location) { + this.position.set(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + } + + public void updateFireDisplay() { + this.fireDisplay.releaseAll(); + if (this.isFireVisible()) { + Map fireBones = ModelEngineAPI.getBlueprint("internal_fire").getBones(); + float fireScale = this.width.get() * 1.4F; + if (!TMath.isSimilar(fireScale, 0.0F)) { + float fireWidth = 1.0F; + float fireHeight = this.height.get() / fireScale; + float fireYOffset = 0.0F; + float fireZOffset = 0.3F - (int)fireHeight * 0.02F; + + for (int modelType = 0; fireHeight > 0.0F; modelType++) { + ItemModelData modelData = fireBones.get("fire_" + modelType % 2).getModelData(); + float flip = fireHeight / 2.0F % 2.0F == 0.0F ? -1.0F : 1.0F; + Optional maybeStack = modelData.createItemStack().stream().findFirst(); + if (maybeStack.isPresent()) { + DisplayFire fire = this.fireDisplay.getOrCreate(); + fire.getFireModel().set(maybeStack.get()); + fire.getPosition().set(new Vector3f(0.0F, fireYOffset, fireZOffset).mul(fireScale)); + fire.getScale().set(new Vector3f(flip * fireWidth, 1.4F, 1.0F).mul(fireScale)); + } + + fireHeight -= 0.45F; + fireYOffset += 0.45F; + fireWidth *= 0.9F; + fireZOffset -= 0.03F; + } + } + } + } + + public void setOnFire(boolean flag) { + this.onFire.set(flag, () -> this.fireDisplay.getInUse().forEach(displayFire -> displayFire.getVisible().set(flag))); + this.onFire.clearDirty(); + } + + @Override + public void clearDirty() { + this.width.clearDirty(); + this.height.clearDirty(); + this.shadowRadius.clearDirty(); + this.hitboxVisible.clearDirty(); + this.shadowVisible.clearDirty(); + this.fireVisible.clearDirty(); + this.fireDisplay.getInUse().forEach(DisplayFire::clearDirty); + } + + @Override + public int getPivotId() { + return this.pivotId; + } + + @Override + public UUID getPivotUuid() { + return this.pivotUuid; + } + + @Override + public int getHitboxId() { + return this.hitboxId; + } + + @Override + public UUID getHitboxUuid() { + return this.hitboxUuid; + } + + @Override + public int getShadowId() { + return this.shadowId; + } + + @Override + public UUID getShadowUuid() { + return this.shadowUuid; + } + + @Override + public DataTracker getPosition() { + return this.position; + } + + @Override + public PositionCodec getPositionCodec() { + return this.positionCodec; + } + + @Override + public DataTracker getWidth() { + return this.width; + } + + @Override + public DataTracker getHeight() { + return this.height; + } + + @Override + public DataTracker getShadowRadius() { + return this.shadowRadius; + } + + @Override + public DataTracker getHitboxVisible() { + return this.hitboxVisible; + } + + @Override + public DataTracker getShadowVisible() { + return this.shadowVisible; + } + + @Override + public DataTracker getFireVisible() { + return this.fireVisible; + } + + public DataTracker getOnFire() { + return this.onFire; + } + + @Override + public PooledCollection getFireDisplay() { + return this.fireDisplay; + } + + public HitboxImpl(int pivotId, int hitboxId, int shadowId) { + this.pivotId = pivotId; + this.hitboxId = hitboxId; + this.shadowId = shadowId; + } + } + + public static class PivotImpl implements DisplayRenderer.Pivot { + private PivotOverride pivotOverride; + private Float cameraEye; + private final int id; + private final UUID uuid = UUID.randomUUID(); + private final DataTracker position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final PositionCodec positionCodec = new PositionCodec(); + private final DataTracker yaw = new DataTracker<>(); + private final DataTracker cameraHeight = new DataTracker<>(); + private final CollectionDataTracker passengers = new CollectionDataTracker<>(new HashSet<>()); + + public Vector3f getMountOffset(float eyeHeight) { + if (this.pivotOverride == null) { + return new Vector3f(0.0F, eyeHeight, 0.0F); + } else if (this.cameraEye != null) { + return new Vector3f(0.0F, this.cameraEye, 0.0F); + } else { + Vector3f offset = this.pivotOverride.getMountOffset(); + return offset == null ? new Vector3f(0.0F, eyeHeight, 0.0F) : offset; + } + } + + public void updatePosition(Location location, float eyeHeight) { + Vector3f offset = this.getMountOffset(eyeHeight); + this.position.set(new Vector3f().set(location.getX(), location.getY(), location.getZ()).add(offset)); + } + + @Override + public void clearDirty() { + this.yaw.clearDirty(); + this.position.clearDirty(); + this.passengers.clearDirty(); + this.cameraHeight.clearDirty(); + } + + @Override + public boolean isOverridden() { + return this.pivotOverride != null; + } + + public PivotOverride getPivotOverride() { + return this.pivotOverride; + } + + public Float getCameraEye() { + return this.cameraEye; + } + + @Override + public int getId() { + return this.id; + } + + @Override + public UUID getUuid() { + return this.uuid; + } + + @Override + public DataTracker getPosition() { + return this.position; + } + + @Override + public PositionCodec getPositionCodec() { + return this.positionCodec; + } + + public DataTracker getYaw() { + return this.yaw; + } + + @Override + public DataTracker getCameraHeight() { + return this.cameraHeight; + } + + @Override + public CollectionDataTracker getPassengers() { + return this.passengers; + } + + public PivotImpl(int id) { + this.id = id; + } + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/vfx/VFXImpl.java b/core/src/main/java/com/ticxo/modelengine/core/vfx/VFXImpl.java new file mode 100644 index 0000000..f3037eb --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/vfx/VFXImpl.java @@ -0,0 +1,289 @@ +package com.ticxo.modelengine.core.vfx; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.generator.BaseItemEnum; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.core.vfx.render.VFXDisplayRendererImpl; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Function; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class VFXImpl implements VFX { + private final BaseEntity base; + private final VFXRenderer renderer; + private final Vector3f modelScale = new Vector3f(); + private final boolean initialized; + private final List queuedTask = new ArrayList<>(); + private final DataTracker modelTracker = new DataTracker<>(new ItemStack(Material.AIR)); + private boolean isBaseEntityVisible = true; + private boolean destroyed; + private boolean removed; + private float yaw; + private float pitch; + private Vector origin = new Vector(); + private Vector3f position = new Vector3f(); + private Vector3f rotation = new Vector3f(); + private Vector3f scale = new Vector3f(1.0F); + private Color color; + private boolean enchanted; + private int blockLight = -1; + private int skyLight = -1; + private boolean visible = true; + + public VFXImpl(@NotNull BaseEntity base, @Nullable Function rendererSupplier, @Nullable Consumer consumer) { + this.base = base; + this.setOrigin(base.getLocation().toVector()); + VFXRenderer renderer = (VFXRenderer)(rendererSupplier == null ? new VFXDisplayRendererImpl(this) : rendererSupplier.apply(this)); + this.renderer = (VFXRenderer)(renderer == null ? new VFXDisplayRendererImpl(this) : renderer); + if (consumer != null) { + consumer.accept(this); + } + + this.renderer.initialize(); + synchronized (this.queuedTask) { + this.queuedTask.forEach(Runnable::run); + this.initialized = true; + } + + this.registerSelf(); + } + + @Override + public boolean tick() { + if (!this.initialized) { + return true; + } else { + this.setOrigin(this.base.getLocation().toVector()); + this.setYaw(this.base.getYHeadRot()); + this.setPitch(this.base.getXHeadRot()); + this.renderer.readVFXData(); + return !this.removed && !this.base.isRemoved(); + } + } + + @Override + public void destroy() { + this.destroyed = true; + } + + @Override + public void markRemoved() { + this.removed = true; + } + + @Override + public void queuePostInitTask(Runnable runnable) { + synchronized (this.queuedTask) { + if (this.initialized) { + runnable.run(); + } else { + this.queuedTask.add(runnable); + } + } + } + + @Override + public void setBaseEntityVisible(boolean flag) { + if (this.isBaseEntityVisible() != flag) { + this.isBaseEntityVisible = flag; + this.base.setVisible(flag); + } + } + + @Override + public void setModelScale(int scale) { + this.modelScale.set(scale); + } + + @Override + public ItemStack getModel() { + return this.modelTracker.get(); + } + + @Override + public void setModel(ItemStack stack) { + this.modelTracker.set(stack); + } + + @Override + public void setColor(Color color) { + this.color = color; + ItemStack model = this.modelTracker.get(); + BaseItemEnum base = BaseItemEnum.fromMaterial(model.getType()); + if (base != null) { + ItemMeta meta = model.getItemMeta(); + base.color(meta, color); + model.setItemMeta(meta); + this.modelTracker.markDirty(); + } + } + + @Override + public void setEnchanted(boolean flag) { + if (this.isEnchanted() != flag) { + this.enchanted = flag; + ItemStack model = this.modelTracker.get(); + if (flag) { + model.addUnsafeEnchantment(Enchantment.VANISHING_CURSE, 1); + } else { + model.removeEnchantment(Enchantment.VANISHING_CURSE); + } + + this.modelTracker.markDirty(); + } + } + + @Override + public BaseEntity getBase() { + return this.base; + } + + @Override + public VFXRenderer getRenderer() { + return this.renderer; + } + + public Vector3f getModelScale() { + return this.modelScale; + } + + @Override + public boolean isInitialized() { + return this.initialized; + } + + public List getQueuedTask() { + return this.queuedTask; + } + + @Override + public DataTracker getModelTracker() { + return this.modelTracker; + } + + @Override + public boolean isBaseEntityVisible() { + return this.isBaseEntityVisible; + } + + @Override + public boolean isDestroyed() { + return this.destroyed; + } + + public boolean isRemoved() { + return this.removed; + } + + @Override + public float getYaw() { + return this.yaw; + } + + @Override + public float getPitch() { + return this.pitch; + } + + @Override + public Vector getOrigin() { + return this.origin; + } + + @Override + public Vector3f getPosition() { + return this.position; + } + + @Override + public Vector3f getRotation() { + return this.rotation; + } + + @Override + public Vector3f getScale() { + return this.scale; + } + + @Override + public Color getColor() { + return this.color; + } + + @Override + public boolean isEnchanted() { + return this.enchanted; + } + + @Override + public int getBlockLight() { + return this.blockLight; + } + + @Override + public int getSkyLight() { + return this.skyLight; + } + + @Override + public boolean isVisible() { + return this.visible; + } + + @Override + public void setYaw(float yaw) { + this.yaw = yaw; + } + + @Override + public void setPitch(float pitch) { + this.pitch = pitch; + } + + @Override + public void setOrigin(Vector origin) { + this.origin = origin; + } + + @Override + public void setPosition(Vector3f position) { + this.position = position; + } + + @Override + public void setRotation(Vector3f rotation) { + this.rotation = rotation; + } + + @Override + public void setScale(Vector3f scale) { + this.scale = scale; + } + + @Override + public void setBlockLight(int blockLight) { + this.blockLight = blockLight; + } + + @Override + public void setSkyLight(int skyLight) { + this.skyLight = skyLight; + } + + @Override + public void setVisible(boolean visible) { + this.visible = visible; + } +} diff --git a/core/src/main/java/com/ticxo/modelengine/core/vfx/render/VFXDisplayRendererImpl.java b/core/src/main/java/com/ticxo/modelengine/core/vfx/render/VFXDisplayRendererImpl.java new file mode 100644 index 0000000..1e9c26a --- /dev/null +++ b/core/src/main/java/com/ticxo/modelengine/core/vfx/render/VFXDisplayRendererImpl.java @@ -0,0 +1,193 @@ +package com.ticxo.modelengine.core.vfx.render; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.DataTracker; +import com.ticxo.modelengine.api.utils.data.tracker.UpdateDataTracker; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import java.util.UUID; +import org.bukkit.inventory.ItemStack; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class VFXDisplayRendererImpl implements VFXDisplayRenderer { + private final VFX vfx; + private final EntityHandler entityHandler; + private final VFXRendererParser parser; + private VFXDisplayRendererImpl.VFXModelImpl vfxModel; + private boolean respawnRequired; + private boolean initialized; + + public VFXDisplayRendererImpl(VFX vfx) { + this.vfx = vfx; + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.parser = ModelEngineAPI.getNMSHandler().getVFXRendererParser(this); + } + + @Override + public VFX getVFX() { + return this.vfx; + } + + @Override + public void initialize() { + this.vfxModel = new VFXDisplayRendererImpl.VFXModelImpl( + this.entityHandler.getNextEntityId(), UUID.randomUUID(), this.entityHandler.getNextEntityId(), UUID.randomUUID() + ); + this.vfxModel.getOrigin().set(this.vfx.getOrigin().toVector3f()); + this.vfxModel.getPosition().set(this.calculatePosition()); + this.vfxModel.getLeftRotation().set(this.calculateRotation()); + this.vfxModel.getScale().set(this.vfx.getScale()); + this.vfxModel.getModel().set(this.vfx.isVisible() ? this.vfx.getModel() : null); + this.vfxModel.getBrightness().set(this.vfx.getBrightness()); + this.initialized = true; + this.respawnRequired = true; + } + + @Override + public void readVFXData() { + if (this.initialized) { + this.vfxModel.getOrigin().set(this.vfx.getOrigin().toVector3f()); + this.vfxModel.getPosition().set(this.calculatePosition()); + this.vfxModel.getLeftRotation().set(this.calculateRotation()); + this.vfxModel.getScale().set(this.vfx.getScale()); + this.vfxModel.getBrightness().set(this.vfx.getBrightness()); + if (!this.vfx.isVisible()) { + this.vfxModel.getModel().set(null); + } else { + this.vfxModel.getModel().set(this.vfx.getModel()); + if (this.vfx.getModelTracker().isDirty()) { + this.vfx.getModelTracker().clearDirty(); + this.vfxModel.getModel().markDirty(); + } + } + } + } + + @Override + public void sendToClient() { + if (this.initialized) { + this.parser.sendToClients(this); + } + } + + @Override + public void destroy() { + if (this.initialized) { + this.parser.destroy(this); + } + } + + @Override + public VFXDisplayRenderer.VFXModel getVFXModel() { + return this.vfxModel; + } + + private Vector3f calculatePosition() { + float yaw = this.vfx.getYaw(); + float pitch = this.vfx.getPitch(); + Vector3f pos = this.vfx.getPosition(); + return new Vector3f(pos).rotateX(pitch * (float) (Math.PI / 180.0)).rotateY(-yaw * (float) (Math.PI / 180.0)); + } + + private Quaternionf calculateRotation() { + float yaw = this.vfx.getYaw(); + float pitch = this.vfx.getPitch(); + Vector3f rot = this.vfx.getRotation(); + return new Quaternionf().rotateY((180.0F - yaw) * (float) (Math.PI / 180.0)).rotateX(-pitch * (float) (Math.PI / 180.0)).rotateZYX(rot.z, rot.y, rot.x); + } + + @Override + public boolean isRespawnRequired() { + return this.respawnRequired; + } + + @Override + public void setRespawnRequired(boolean respawnRequired) { + this.respawnRequired = respawnRequired; + } + + @Override + public boolean isInitialized() { + return this.initialized; + } + + public static class VFXModelImpl implements VFXDisplayRenderer.VFXModel { + private final int pivotId; + private final UUID pivotUuid; + private final int modelId; + private final UUID modelUuid; + private final DataTracker origin = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final PositionCodec positionCodec = new PositionCodec(); + private final DataTracker position = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final DataTracker leftRotation = new UpdateDataTracker<>(new Quaternionf(), Quaternionf::set); + private final DataTracker scale = new UpdateDataTracker<>(new Vector3f(), Vector3f::set); + private final DataTracker model = new DataTracker<>(); + private final DataTracker brightness = new DataTracker<>(-1); + + @Override + public int getPivotId() { + return this.pivotId; + } + + @Override + public UUID getPivotUuid() { + return this.pivotUuid; + } + + @Override + public int getModelId() { + return this.modelId; + } + + @Override + public UUID getModelUuid() { + return this.modelUuid; + } + + @Override + public DataTracker getOrigin() { + return this.origin; + } + + @Override + public PositionCodec getPositionCodec() { + return this.positionCodec; + } + + @Override + public DataTracker getPosition() { + return this.position; + } + + @Override + public DataTracker getLeftRotation() { + return this.leftRotation; + } + + @Override + public DataTracker getScale() { + return this.scale; + } + + @Override + public DataTracker getModel() { + return this.model; + } + + @Override + public DataTracker getBrightness() { + return this.brightness; + } + + public VFXModelImpl(int pivotId, UUID pivotUuid, int modelId, UUID modelUuid) { + this.pivotId = pivotId; + this.pivotUuid = pivotUuid; + this.modelId = modelId; + this.modelUuid = modelUuid; + } + } +} diff --git a/core/src/main/resources/config.yml b/core/src/main/resources/config.yml new file mode 100644 index 0000000..ca838cc --- /dev/null +++ b/core/src/main/resources/config.yml @@ -0,0 +1,86 @@ +Model-Engine: + Print-Script-Warnings: false + Use-State-Machine: false + Engine-Threads: 4 + Max-Engine-Threads: 10 + Default-Animations: + IDLE: idle + WALK: walk + STRAFE: strafe + JUMP_START: jump_start + JUMP: jump + JUMP_END: jump_end + HOVER: hover + FLY: fly + SPAWN: spawn + DEATH: death + Sync-Client-Tick-End: true + Load-On-World-Load: false + Unload-On-World-Unload: false + Manual-Translucency-Order: false + Default-Animation-Priority: 0 + Client-Sync-Interval: 60000 + Lower-Scale-Limit: 0.005 + Force-Custom-Model-Data: false + Process-Empty-Timeline: false + Render-Fire-On-Model: true + MineSkin-API-Key: + User-Limb: + Eager-Generate-Skins: true + Default-Classic-Skin: Steve + Default-Slim-Skin: Alex + Default-Skins: + Steve: + base64: iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAdVBMVEUAAAAKvLwAzMwmGgokGAgrHg0zJBE/KhW3g2uzeV5SPYn///+qclmbY0mQWT8Af38AaGhVVVWUYD52SzOBUzmPXj5JJRBCHQp3QjVqQDA0JRIoKCg3Nzc/Pz9KSko6MYlBNZtGOqUDenoFiIgElZUApKQAr6/wvakZAAAAAXRSTlMAQObYZgAAAolJREFUeNrt1l1rHucZReFrj/whu5hSCCQtlOTE/f+/Jz4q9Cu0YIhLcFVpVg+FsOCVehi8jmZgWOzZz33DM4CXlum3gH95GgeAzQZVeL4gTm6Cbp4vqFkD8HwBazPY8wWbMq9utu3mNZ5fotVezbzOE3kBEFbaZuc8kb00NTMUbWJp678Xf2GV7RRtx1TDQQ6XBNvsmL2+2vHq1TftmMPIyAWujtN2cl274ua2jpVpZneXEjjo7XW1q53V9ds4ODO5xIuhvGHvfLI3aixauig415uuO2+vl9+cncfsFw25zL650fXn687jqnXuP68/X3+eV3zE7y6u9eB73MlfAcfbTf3yR8CfAX+if8S/H5/EAbAxj5LN48tULvEBOh8V1AageMTXe2YHAOwHbZxrzPkSR3+ffr8TR2JDzE/4Fj8CDgEwDsW+q+9GsR07hhg2CsALBgMo2v5wNxXnQXMeGQVW7gUAyKI2m6KDsJ8Au3++F5RZO+kKNQjQcLLWgjwUjBXLltFgWWMUUlviocBgNoxNGgMjSxiYAA7zgLFo2hgIENiDU8gQCzDOmViGFAsEuBcQSDCothhpJaDRA8E5fHqH2nTbYm5fHLo1V0u3B7DAuheoeScRYabjjjuzs17cHVaTrTXmK78m9swP34d9oK/dfeXSIH2PW/MXwPvxN/bJlxw8zlYAcEyeI6gNgA/O8P8neN8xe1IHP2gTzegjvhUDfuRygmwEs2GE4mkCDIAzm2R4yAuPsIdR9k8AvMc+3L9+2UEjo4WP0FpgP19O0MzCsqxIoMsdDBvYcQyGmO0ZJRoYCKjLJWY0BAhYwGUBCgkh8MRdOKt+ruqMwAB2OcEX94U1TPbYJP0PkyyAI1S6cSIAAAAASUVORK5CYII= + Alex: + base64: iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAZlBMVEUAAAD////v2r/r0LDvu7HfxKLUt4/zqFiUyJKMvorrmD+GuYTljT97snjegS5xq26UlmuAglpvb29lZWV8Vz51UDhYWFhyTjZPT09sRi5kQSwjYiQrVChcOyc/Pz82NjYYOBYoKCgm8xoJAAAAAXRSTlMAQObYZgAAAwZJREFUeNrtlu1W6jAQRWtjWiaZtCC9/YgC8v4vec9Mg6Uur6b8ve6S0Lo8O2NYmClusOMGF7Nr8HKu2IoDTYPk44K6lvBciePNAm7mlTGz3G2voAaYZg9vFzCCjtnZqoHjAYHDJjAM1tqqgmR7Bahf9tFaA6zND6JwXRpxxosZIkz4uQzOWFmTrJPOUgdjOP1hzu7flmNrJe4wtCBoMgR1LVE1mNIYNbAurpafN5N5Xto8vZbl65PhWg0aRiU/C2Rpa0x5w/LHnjQwZVTgGk755+eyNMbWXDeukQIwMjaRm6qyJjmMtTAi1ziHF0OQQwsul+u1SJBnZsTbRJEgIqzxD8H1erksAt80MLTtCawFpvpScDqtKzhUYpA8yKgAv7Wq4GCripmT4PsKPFGIQxdjbFsPCPiDsbY6tAvBU2K+KRZiCHHquimC0ylGCoH8vjSmVEG4xb0Mmb2MYmGYpgH5boBA7iAIPuxL5CUtT0Q72u0wy6SDioVOosh3k5ggQIZgQB4iDITlOqwoFiaJwzJAcMJARhOShUCX3AGjWMWYYqHv+zghHntwPPaoWQJh58mLRe5FUSpQ6BenWDgi1B81rCAki0oIgiDvQRRlMkh+JdDgi2b78zieEUKEWglRG4gQp+8EEupTeOz78f39/U32n1oKb3iAQ642CWQfPlWAUAr3MtoQ2jck4XmTe7wL7ykPrFkJRkm9HCUuopF8CN6TXsGTEAjvt2+7Gu4Fl/N5xN+PMs6XCwZJLv4BER480MzHFsyfwi9ZpDNSYH7IIKcDPKB4iHSwPk7tVo974ZDYZ1VQ/PKfg9Nsddg6ouWfyCMNh2OqzBbBCdxXUDMq2Cq4r6CmDRVEoRvm4z4Q8OwowdmCbgDThEq8Jwg8pb4gSzANU5cY4l1ngCtDMM0NR4yYwfS5LzgoewXPXwuQ1bZDsIJJ2OJHPvcL49wQJEyGQI+5pV/o9Sj8IKcCSd31C5sFEhrv+gVrzAbBul9QINiwB+t+QdHWLBmyPgXtF8CtX5CO4LsK/gL4WlU0/HKH/gAAAABJRU5ErkJggg== + slim: true +Model-Generator: + Register-Post-Server: false + Assets-Post-Server: true + Compile-Post-Server: true + Enable-Error: true + Debug-Level: 1 + Log-Only-Error-Models: false + Namespace: modelengine + Create-Zip: true + Merge-Item-Models: false + Create-Atlas: true + Create-Shader: true + Disabled-Overlays: [] + Create-MC-META: true + Item-Model: LEATHER_HORSE_ARMOR + Item-Models: [] +Network-Optimization: + Bundle-Everything: false + Bundle-Size: 512 + Cull-Interval: 4 + Culling-Threads: 4 + Max-Culling-Threads: 10 + Vertical-Render-Distance: + Enabled: true + Vertical-Render-Distance: 32 + Cull-Type: CULLED + Skip-Models-Behind-Viewer: + Enabled: true + View-Angle: 180 + Force-Render-Radius: 5 + Cull-Type: MOVEMENT_ONLY + Skip-Blocked-Models: + Enabled: true + Force-Render-Radius: 5 + Cull-Type: CULLED + Use-Paper-Clip-Method: false + Force-Render-Size: + Width: 32 + Height: 32 + Reduce-Update-When-Far: + Enabled: true + Active-By-Default: true + Falloff-Length: 8 + Falloff-Multiplier: 0.65 + Full-Update-Distance: 8 + Full-Update-Distance-Multiplier-By-Size: 1 + Max-Rate-Multiplier: 1 + Min-Rate-Multiplier: 0.05 + Override-Move-To-Method: true diff --git a/core/src/main/resources/internal/alex_mapped.bbmodel b/core/src/main/resources/internal/alex_mapped.bbmodel new file mode 100644 index 0000000..9b050af --- /dev/null +++ b/core/src/main/resources/internal/alex_mapped.bbmodel @@ -0,0 +1,1300 @@ +{ + "meta": { + "format_version": "5.0", + "model_format": "free", + "box_uv": false + }, + "name": "alex_mapped", + "model_identifier": "", + "visible_box": [1, 1, 0], + "variable_placeholders": "", + "variable_placeholder_buttons": [], + "timeline_setups": [], + "unhandled_root_fields": {}, + "resolution": { + "width": 16, + "height": 16 + }, + "elements": [ + { + "name": "Head", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 24, -4], + "to": [4, 32, 4], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "faces": { + "north": { + "uv": [8, 8, 16, 16], + "texture": 0 + }, + "east": { + "uv": [0, 8, 8, 16], + "texture": 0 + }, + "south": { + "uv": [24, 8, 32, 16], + "texture": 0 + }, + "west": { + "uv": [16, 8, 24, 16], + "texture": 0 + }, + "up": { + "uv": [16, 8, 8, 0], + "texture": 0 + }, + "down": { + "uv": [24, 0, 16, 8], + "texture": 0 + } + }, + "type": "cube", + "uuid": "773085fd-ece5-a5b9-5e19-73fd8aa66ffb" + }, + { + "name": "Hat Layer", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 24, -4], + "to": [4, 32, 4], + "autouv": 0, + "color": 0, + "inflate": 0.5, + "origin": [0, 0, 0], + "uv_offset": [32, 0], + "faces": { + "north": { + "uv": [40, 8, 48, 16], + "texture": 0 + }, + "east": { + "uv": [32, 8, 40, 16], + "texture": 0 + }, + "south": { + "uv": [56, 8, 64, 16], + "texture": 0 + }, + "west": { + "uv": [48, 8, 56, 16], + "texture": 0 + }, + "up": { + "uv": [48, 8, 40, 0], + "texture": 0 + }, + "down": { + "uv": [56, 0, 48, 8], + "texture": 0 + } + }, + "type": "cube", + "uuid": "57175ec5-3265-02a0-2add-cd194f195826" + }, + { + "name": "body", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 12, -2], + "to": [4, 16, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 16], + "faces": { + "north": { + "uv": [20, 28, 28, 32], + "texture": 0 + }, + "east": { + "uv": [16, 28, 20, 32], + "texture": 0 + }, + "south": { + "uv": [32, 28, 40, 32], + "texture": 0 + }, + "west": { + "uv": [28, 28, 32, 32], + "texture": 0 + }, + "up": { + "uv": [28, 29, 20, 28], + "texture": 0 + }, + "down": { + "uv": [36, 16, 28, 20], + "texture": 0 + } + }, + "type": "cube", + "uuid": "55511b53-fdf3-ec80-d1df-2a30a7ab059e" + }, + { + "name": "hat_body", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 12, -2], + "to": [4, 16, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [16, 32], + "faces": { + "north": { + "uv": [20, 44, 28, 48], + "texture": 0 + }, + "east": { + "uv": [16, 44, 20, 48], + "texture": 0 + }, + "south": { + "uv": [32, 44, 40, 48], + "texture": 0 + }, + "west": { + "uv": [28, 44, 32, 48], + "texture": 0 + }, + "up": { + "uv": [8, 4, 0, 0], + "texture": 1 + }, + "down": { + "uv": [36, 32, 28, 36], + "texture": 0 + } + }, + "type": "cube", + "uuid": "47af0790-f0dc-a2dc-0018-82b2ddea8ad7" + }, + { + "name": "right_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 20, -2], + "to": [7, 24, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [40, 16], + "faces": { + "north": { + "uv": [44, 20, 47, 24], + "texture": 0 + }, + "east": { + "uv": [40, 20, 44, 24], + "texture": 0 + }, + "south": { + "uv": [51, 20, 54, 24], + "texture": 0 + }, + "west": { + "uv": [47, 20, 51, 24], + "texture": 0 + }, + "up": { + "uv": [47, 20, 44, 16], + "texture": 0 + }, + "down": { + "uv": [47, 23, 44, 24], + "texture": 0 + } + }, + "type": "cube", + "uuid": "48c97cc9-2210-280a-019a-468b7de7c38f" + }, + { + "name": "hat_right_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 20, -2], + "to": [7, 24, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [40, 32], + "faces": { + "north": { + "uv": [44, 36, 47, 40], + "texture": 0 + }, + "east": { + "uv": [40, 36, 44, 40], + "texture": 0 + }, + "south": { + "uv": [51, 36, 54, 40], + "texture": 0 + }, + "west": { + "uv": [47, 36, 51, 40], + "texture": 0 + }, + "up": { + "uv": [47, 36, 44, 32], + "texture": 0 + }, + "down": { + "uv": [4, 0, 0, 4], + "texture": 1 + } + }, + "type": "cube", + "uuid": "5003d649-ffbd-da45-da99-db3ced59a92a" + }, + { + "name": "left_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-7, 20, -2], + "to": [-4, 24, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [32, 48], + "faces": { + "north": { + "uv": [36, 52, 39, 56], + "texture": 0 + }, + "east": { + "uv": [32, 52, 36, 56], + "texture": 0 + }, + "south": { + "uv": [43, 52, 46, 56], + "texture": 0 + }, + "west": { + "uv": [39, 52, 43, 56], + "texture": 0 + }, + "up": { + "uv": [39, 52, 36, 48], + "texture": 0 + }, + "down": { + "uv": [39, 55, 36, 56], + "texture": 0 + } + }, + "type": "cube", + "uuid": "1d2562ed-3d0d-1e7b-ad42-46494c3d3f6a" + }, + { + "name": "hat_left_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-7, 20, -2], + "to": [-4, 24, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [48, 48], + "faces": { + "north": { + "uv": [52, 52, 55, 56], + "texture": 0 + }, + "east": { + "uv": [48, 52, 52, 56], + "texture": 0 + }, + "south": { + "uv": [59, 52, 62, 56], + "texture": 0 + }, + "west": { + "uv": [55, 52, 59, 56], + "texture": 0 + }, + "up": { + "uv": [55, 52, 52, 48], + "texture": 0 + }, + "down": { + "uv": [59, 48, 56, 52], + "texture": 1 + } + }, + "type": "cube", + "uuid": "8ed52da2-9b81-09f5-5905-eba9174b8eed" + }, + { + "name": "right_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 8, -2], + "to": [3.9, 12, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [0, 16], + "faces": { + "north": { + "uv": [4, 20, 8, 24], + "texture": 0 + }, + "east": { + "uv": [0, 20, 4, 24], + "texture": 0 + }, + "south": { + "uv": [12, 20, 16, 24], + "texture": 0 + }, + "west": { + "uv": [8, 20, 12, 24], + "texture": 0 + }, + "up": { + "uv": [8, 20, 4, 16], + "texture": 0 + }, + "down": { + "uv": [8, 23, 4, 24], + "texture": 0 + } + }, + "type": "cube", + "uuid": "ff747326-cd74-c195-704e-ef28f7c5d8f2" + }, + { + "name": "hat_right_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 8, -2], + "to": [3.9, 12, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 32], + "faces": { + "north": { + "uv": [4, 36, 8, 40], + "texture": 0 + }, + "east": { + "uv": [0, 36, 4, 40], + "texture": 0 + }, + "south": { + "uv": [12, 36, 16, 40], + "texture": 0 + }, + "west": { + "uv": [8, 36, 12, 40], + "texture": 0 + }, + "up": { + "uv": [8, 36, 4, 32], + "texture": 0 + }, + "down": { + "uv": [12, 32, 8, 36], + "texture": 1 + } + }, + "type": "cube", + "uuid": "0cd5a793-5d97-dc7c-5604-561faf7822c3" + }, + { + "name": "left_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 8, -2], + "to": [0.1, 12, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 48], + "faces": { + "north": { + "uv": [20, 52, 24, 56], + "texture": 0 + }, + "east": { + "uv": [16, 52, 20, 56], + "texture": 0 + }, + "south": { + "uv": [28, 52, 32, 56], + "texture": 0 + }, + "west": { + "uv": [24, 52, 28, 56], + "texture": 0 + }, + "up": { + "uv": [24, 52, 20, 48], + "texture": 0 + }, + "down": { + "uv": [24, 55, 20, 56], + "texture": 0 + } + }, + "type": "cube", + "uuid": "572cbd8d-3a02-5d54-cc8e-aad0616dbec4" + }, + { + "name": "hat_left_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 8, -2], + "to": [0.1, 12, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 48], + "faces": { + "north": { + "uv": [4, 52, 8, 56], + "texture": 0 + }, + "east": { + "uv": [0, 52, 4, 56], + "texture": 0 + }, + "south": { + "uv": [12, 52, 16, 56], + "texture": 0 + }, + "west": { + "uv": [8, 52, 12, 56], + "texture": 0 + }, + "up": { + "uv": [8, 52, 4, 48], + "texture": 0 + }, + "down": { + "uv": [12, 48, 8, 52], + "texture": 1 + } + }, + "type": "cube", + "uuid": "69fe31ce-0ba6-2c2d-6021-7a25b20b9770" + }, + { + "name": "hat_chest", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 16, -2], + "to": [4, 24, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [16, 32], + "faces": { + "north": { + "uv": [20, 36, 28, 44], + "texture": 0 + }, + "east": { + "uv": [16, 36, 20, 44], + "texture": 0 + }, + "south": { + "uv": [32, 36, 40, 44], + "texture": 0 + }, + "west": { + "uv": [28, 36, 32, 44], + "texture": 0 + }, + "up": { + "uv": [28, 36, 20, 32], + "texture": 0 + }, + "down": { + "uv": [8, 0, 0, 4], + "texture": 1 + } + }, + "type": "cube", + "uuid": "b767ac81-4abb-495c-c293-de417ee14797" + }, + { + "name": "chest", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 16, -2], + "to": [4, 24, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 16], + "faces": { + "north": { + "uv": [20, 20, 28, 28], + "texture": 0 + }, + "east": { + "uv": [16, 20, 20, 28], + "texture": 0 + }, + "south": { + "uv": [32, 20, 40, 28], + "texture": 0 + }, + "west": { + "uv": [28, 20, 32, 28], + "texture": 0 + }, + "up": { + "uv": [28, 20, 20, 16], + "texture": 0 + }, + "down": { + "uv": [28, 27, 20, 28], + "texture": 0 + } + }, + "type": "cube", + "uuid": "104ecd06-18b8-404b-0f37-8d51b98891fa" + }, + { + "name": "right_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 12, -2], + "to": [7, 20, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [40, 16], + "faces": { + "north": { + "uv": [44, 24, 47, 32], + "texture": 0 + }, + "east": { + "uv": [40, 24, 44, 32], + "texture": 0 + }, + "south": { + "uv": [51, 24, 54, 32], + "texture": 0 + }, + "west": { + "uv": [47, 24, 51, 32], + "texture": 0 + }, + "up": { + "uv": [47, 25, 44, 24], + "texture": 0 + }, + "down": { + "uv": [50, 16, 47, 20], + "texture": 0 + } + }, + "type": "cube", + "uuid": "38ed858d-8c7c-e8d1-0020-d597fac38034" + }, + { + "name": "hat_right_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 12, -2], + "to": [7, 20, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [40, 32], + "faces": { + "north": { + "uv": [44, 40, 47, 48], + "texture": 0 + }, + "east": { + "uv": [40, 40, 44, 48], + "texture": 0 + }, + "south": { + "uv": [51, 40, 54, 48], + "texture": 0 + }, + "west": { + "uv": [47, 40, 51, 48], + "texture": 0 + }, + "up": { + "uv": [3, 4, 0, 0], + "texture": 1 + }, + "down": { + "uv": [50, 32, 47, 36], + "texture": 0 + } + }, + "type": "cube", + "uuid": "6ad770bd-3bac-08fd-d5b7-138e26e069c8" + }, + { + "name": "left_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-7, 12, -2], + "to": [-4, 20, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [32, 48], + "faces": { + "north": { + "uv": [36, 56, 39, 64], + "texture": 0 + }, + "east": { + "uv": [32, 56, 36, 64], + "texture": 0 + }, + "south": { + "uv": [43, 56, 46, 64], + "texture": 0 + }, + "west": { + "uv": [39, 56, 43, 64], + "texture": 0 + }, + "up": { + "uv": [39, 57, 36, 56], + "texture": 0 + }, + "down": { + "uv": [42, 48, 39, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "07d13b5d-5740-9daf-9c96-e24527450262" + }, + { + "name": "hat_left_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-7, 12, -2], + "to": [-4, 20, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [48, 48], + "faces": { + "north": { + "uv": [52, 56, 55, 64], + "texture": 0 + }, + "east": { + "uv": [48, 56, 52, 64], + "texture": 0 + }, + "south": { + "uv": [59, 56, 62, 64], + "texture": 0 + }, + "west": { + "uv": [55, 56, 59, 64], + "texture": 0 + }, + "up": { + "uv": [55, 52, 52, 48], + "texture": 1 + }, + "down": { + "uv": [58, 48, 55, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "f29d51fc-42be-bd31-8d5b-5d3856518722" + }, + { + "name": "left_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 0, -2], + "to": [0.1, 8, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 48], + "faces": { + "north": { + "uv": [20, 56, 24, 64], + "texture": 0 + }, + "east": { + "uv": [16, 56, 20, 64], + "texture": 0 + }, + "south": { + "uv": [28, 56, 32, 64], + "texture": 0 + }, + "west": { + "uv": [24, 56, 28, 64], + "texture": 0 + }, + "up": { + "uv": [24, 57, 20, 56], + "texture": 0 + }, + "down": { + "uv": [28, 48, 24, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "6e9969e8-9486-ce88-685d-f9d885b2d393" + }, + { + "name": "hat_left_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 0, -2], + "to": [0.1, 8, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 48], + "faces": { + "north": { + "uv": [4, 56, 8, 64], + "texture": 0 + }, + "east": { + "uv": [0, 56, 4, 64], + "texture": 0 + }, + "south": { + "uv": [12, 56, 16, 64], + "texture": 0 + }, + "west": { + "uv": [8, 56, 12, 64], + "texture": 0 + }, + "up": { + "uv": [8, 52, 4, 48], + "texture": 1 + }, + "down": { + "uv": [12, 48, 8, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "cb210e40-f438-8286-da38-58c7c98a1d8f" + }, + { + "name": "right_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 0, -2], + "to": [3.9, 8, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [0, 16], + "faces": { + "north": { + "uv": [4, 24, 8, 32], + "texture": 0 + }, + "east": { + "uv": [0, 24, 4, 32], + "texture": 0 + }, + "south": { + "uv": [12, 24, 16, 32], + "texture": 0 + }, + "west": { + "uv": [8, 24, 12, 32], + "texture": 0 + }, + "up": { + "uv": [8, 25, 4, 24], + "texture": 0 + }, + "down": { + "uv": [12, 16, 8, 20], + "texture": 0 + } + }, + "type": "cube", + "uuid": "4790240d-8caa-c1a7-29c0-fb662f6ed69c" + }, + { + "name": "hat_right_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 0, -2], + "to": [3.9, 8, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 32], + "faces": { + "north": { + "uv": [4, 40, 8, 48], + "texture": 0 + }, + "east": { + "uv": [0, 40, 4, 48], + "texture": 0 + }, + "south": { + "uv": [12, 40, 16, 48], + "texture": 0 + }, + "west": { + "uv": [8, 40, 12, 48], + "texture": 0 + }, + "up": { + "uv": [8, 36, 4, 32], + "texture": 1 + }, + "down": { + "uv": [12, 32, 8, 36], + "texture": 0 + } + }, + "type": "cube", + "uuid": "bf00419f-2747-6d7d-6750-74cc60fae501" + } + ], + "groups": [ + { + "uuid": "5400c1a6-94b7-0533-294c-37501ba32de5", + "export": true, + "locked": false, + "origin": [0, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "waist", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "278df701-6051-1ac3-a7ab-29a01a41c308", + "export": true, + "locked": false, + "origin": [0, 24, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "head", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": false + }, + { + "uuid": "23943758-ce52-7338-6c0c-353096f8338a", + "export": true, + "locked": false, + "origin": [0, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "body", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "f0181c5c-a850-6a70-ebe8-7706c029231d", + "export": true, + "locked": false, + "origin": [5, 22, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "right_arm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "30ebd0e3-f52f-8023-f330-6653c3ebad9d", + "export": true, + "locked": false, + "origin": [-5, 22, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "left_arm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "6a354ac6-dbab-f460-deda-6f279c2311e6", + "export": true, + "locked": false, + "origin": [1.9, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "right_leg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "7e18703d-ce68-fb92-4e63-d0414f7f43ee", + "export": true, + "locked": false, + "origin": [-1.9, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "left_leg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "05c86cb0-39d8-f6ae-8349-ab0e5cbc25ef", + "export": true, + "locked": false, + "origin": [0, 16, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "chest", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "a71e3bf3-9dfc-6adb-f652-e1ad0b84539e", + "export": true, + "locked": false, + "origin": [6, 20, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "right_forearm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "0da46e14-aaab-9e07-5252-a78c28cb0a23", + "export": true, + "locked": false, + "origin": [-6, 20, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "left_forearm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "9d962bea-0e4b-fdf9-35dd-3d5266462cec", + "export": true, + "locked": false, + "origin": [0, 0, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "root", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "01f1fb2f-972d-1d69-8d72-6e908af47da3", + "export": true, + "locked": false, + "origin": [-1.9, 8, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "left_foreleg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "d77c33f0-fa52-d727-f6f0-7fa68d177d51", + "export": true, + "locked": false, + "origin": [1.9, 8, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "right_foreleg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + } + ], + "outliner": [ + { + "uuid": "9d962bea-0e4b-fdf9-35dd-3d5266462cec", + "isOpen": true, + "children": [ + { + "uuid": "5400c1a6-94b7-0533-294c-37501ba32de5", + "isOpen": true, + "children": [ + { + "uuid": "23943758-ce52-7338-6c0c-353096f8338a", + "isOpen": true, + "children": [ + { + "uuid": "05c86cb0-39d8-f6ae-8349-ab0e5cbc25ef", + "isOpen": true, + "children": [ + { + "uuid": "278df701-6051-1ac3-a7ab-29a01a41c308", + "isOpen": false, + "children": ["773085fd-ece5-a5b9-5e19-73fd8aa66ffb", "57175ec5-3265-02a0-2add-cd194f195826"] + }, + { + "uuid": "30ebd0e3-f52f-8023-f330-6653c3ebad9d", + "isOpen": true, + "children": [ + "1d2562ed-3d0d-1e7b-ad42-46494c3d3f6a", + "8ed52da2-9b81-09f5-5905-eba9174b8eed", + { + "uuid": "0da46e14-aaab-9e07-5252-a78c28cb0a23", + "isOpen": true, + "children": ["07d13b5d-5740-9daf-9c96-e24527450262", "f29d51fc-42be-bd31-8d5b-5d3856518722"] + } + ] + }, + { + "uuid": "f0181c5c-a850-6a70-ebe8-7706c029231d", + "isOpen": true, + "children": [ + "48c97cc9-2210-280a-019a-468b7de7c38f", + "5003d649-ffbd-da45-da99-db3ced59a92a", + { + "uuid": "a71e3bf3-9dfc-6adb-f652-e1ad0b84539e", + "isOpen": true, + "children": ["38ed858d-8c7c-e8d1-0020-d597fac38034", "6ad770bd-3bac-08fd-d5b7-138e26e069c8"] + } + ] + }, + "104ecd06-18b8-404b-0f37-8d51b98891fa", + "b767ac81-4abb-495c-c293-de417ee14797" + ] + }, + "55511b53-fdf3-ec80-d1df-2a30a7ab059e", + "47af0790-f0dc-a2dc-0018-82b2ddea8ad7" + ] + }, + { + "uuid": "7e18703d-ce68-fb92-4e63-d0414f7f43ee", + "isOpen": true, + "children": [ + "572cbd8d-3a02-5d54-cc8e-aad0616dbec4", + "69fe31ce-0ba6-2c2d-6021-7a25b20b9770", + { + "uuid": "01f1fb2f-972d-1d69-8d72-6e908af47da3", + "isOpen": true, + "children": ["6e9969e8-9486-ce88-685d-f9d885b2d393", "cb210e40-f438-8286-da38-58c7c98a1d8f"] + } + ] + }, + { + "uuid": "6a354ac6-dbab-f460-deda-6f279c2311e6", + "isOpen": true, + "children": [ + "ff747326-cd74-c195-704e-ef28f7c5d8f2", + "0cd5a793-5d97-dc7c-5604-561faf7822c3", + { + "uuid": "d77c33f0-fa52-d727-f6f0-7fa68d177d51", + "isOpen": true, + "children": ["4790240d-8caa-c1a7-29c0-fb662f6ed69c", "bf00419f-2747-6d7d-6750-74cc60fae501"] + } + ] + } + ] + } + ] + } + ], + "textures": [ + { + "name": "", + "path": "", + "folder": "", + "namespace": "", + "id": "0", + "group": "", + "width": 64, + "height": 64, + "uv_width": 64, + "uv_height": 64, + "particle": false, + "use_as_default": false, + "layers_enabled": false, + "sync_to_project": "", + "render_mode": "default", + "render_sides": "auto", + "pbr_channel": "color", + "frame_time": 1, + "frame_order_type": "loop", + "frame_order": "", + "frame_interpolate": false, + "visible": true, + "internal": true, + "saved": false, + "uuid": "141da3cc-5b94-4b80-7421-e066a92662f1", + "source": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAEc0lEQVR4AeyaPWsVQRSG595GISlEwVyI+IGKjT8gvZZioTaSQvwF4kdjsLCQVOpfEItgpZVlBMv8ABtR8QODN6JWCcbGK++SBw6Tc2fGu6TYvRt4eefcd87ZmbOT2Zmd7YfM38s3n0cpXL5+Z5RCJnxWTl1bWura0nIXyCZAARZOHQkews7f/NwgeNiRa9OFs8d6Hgj8/MnDngf0FBclIBWg6VqXgKbfwbrt70ZA3Qw23b9oBKy9/xo80Pn1jWHwgF6X9bjzQFw97jygp7h/bvholMKz4aGQwtPTB0MK2x9ujVJIXVta6trSUteWlrq2tGoELMwdDh7I3PHBTPCAPnPiaPCAvm/+TPCA/mpwu+cBfeX8bM8D+uzSUs8D+v6Tj3sepFcJUGFaUZSAS/MhCCRJZQG7yVyUgCZ3MNf2ogS8WA9BIJjKAnaTuSgBTe5gru1VAtY2vgcPOH8abgUP6FsfvwQP6H/W3wYP6HrceUBfXN0ceUDfXF4eeUDX4w5Ylt6PHz83f1wJFtsr94NF/DiKHz+vLy4Gi9XfN4LF4oN+sDhw91uwiNsTX+/q4GcAate1d7+CELcD23v82d+qEaBMWLD35zf2+tg5xj9m/IgXM3qOFZc6ikF5EnYTMEmgpvq4CWDdT6dY52PnGP+Y8SNezOg5VlzqKAblSXjXXkDrawutpy3sJKJyPHlZX69sY6m8cu9vsFBMi1R8+QNNgtavNBnVCGAfgBPrfmzW+dis67HH+RMHpv64eMSFqe/FR/NioZVwlYCSim2t0yWgrXe2tF/dCCjNVFvrdSOgrXe2tF/dCCjNVFvrVSOAdwF0kr0/Nnt9bPb22OP8iQNTf1w84sLU9+KjebHQxDnseh/AXhvWXtvC7qVVjvfv+I1jG0tl+25AZcW0SMWXP9D+3/rlOo5ejQAMmLN4bM7esXOMf8z4ES9m9BwrLnUUg/Ik7CZgkkBN9XETwDkcneLcDTvH+MeMH/FiRs+x4lJHMShPwt37AGWNiUZlgReRKguaYASVBSYblYVx/sSBVVdQLEFlgXgxSxO8+PpdUBxBZUExxKVw/wVKndtQr0tAG+5inT50I6BO9trg242ANtzFOn3oRkCd7LXBtxoBHD/RIc7isXXsJGBzBIU9zp84MPUVS8AmXszoXnw0xRGwFYNyCe/5+wCd4Vto2WqhpatF/C0B3w6wHGZZLbZxVFYc/LVh0kYJjEtGNQJiUfttgd+15xawc6zze4F6OsMXsHMc++bqx3rc9li3tpsAW6HtZTcBGj4Cnc8NI+rBOr8XsHWGL2DnOPbN1Y/1uO2xbu09fx/A+T2sScqCCQ623xTgI9ZEZ/3oBH7w//pXI4AJhqCaYARsTTACtiYbAds7v9c3AejeGb6+AUD3/NE8XzTYaz+a2i1g23brtyoBKkwrugRM652n390IIBPTyt0ImNY7T7+7EUAmppWrEcAykiSU7t+p753f65sAdO8MX98AoHv+aJ4vmljw2q/fBS2hBZUFLafF4B8AAAD//8kRp90AAAAGSURBVAMAA48UmwfNBaQAAAAASUVORK5CYII=" + }, + { + "name": "color_fetch", + "path": "", + "folder": "block", + "namespace": "", + "id": "1", + "group": "", + "width": 16, + "height": 16, + "uv_width": 16, + "uv_height": 16, + "particle": false, + "use_as_default": false, + "layers_enabled": false, + "sync_to_project": "", + "render_mode": "default", + "render_sides": "auto", + "pbr_channel": "color", + "frame_time": 1, + "frame_order_type": "loop", + "frame_order": "", + "frame_interpolate": false, + "visible": true, + "internal": true, + "saved": false, + "uuid": "7c2f025b-2b7e-fa39-5c27-e509cca95248", + "source": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAJUlEQVR4AeyTsQ0AAAyCSP8/uvEGN4MHOBA4ynkAMpBBMhrw4AEAAP//uBwiawAAAAZJREFUAwBJIAAhJFoqZwAAAABJRU5ErkJggg==" + } + ] +} \ No newline at end of file diff --git a/core/src/main/resources/internal/internal_fire.bbmodel b/core/src/main/resources/internal/internal_fire.bbmodel new file mode 100644 index 0000000..92db71d --- /dev/null +++ b/core/src/main/resources/internal/internal_fire.bbmodel @@ -0,0 +1,258 @@ +{ + "meta": { + "format_version": "5.0", + "model_format": "free", + "box_uv": false + }, + "name": "internal_fire", + "model_identifier": "", + "visible_box": [1, 1, 0], + "variable_placeholders": "", + "variable_placeholder_buttons": [], + "timeline_setups": [], + "unhandled_root_fields": {}, + "resolution": { + "width": 16, + "height": 16 + }, + "elements": [ + { + "name": "cube", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-8, 0, 0], + "to": [8, 16, 0], + "autouv": 1, + "color": 6, + "origin": [0, 0, 0], + "faces": { + "north": { + "uv": [0, 0, 16, 16], + "texture": 0 + }, + "east": { + "uv": [0, 0, 0, 16] + }, + "south": { + "uv": [0, 0, 16, 16], + "texture": 0 + }, + "west": { + "uv": [0, 0, 0, 16] + }, + "up": { + "uv": [0, 0, 16, 0] + }, + "down": { + "uv": [0, 0, 16, 0] + } + }, + "type": "cube", + "uuid": "ee087d96-806e-3a44-4a38-ba3359e8df01" + }, + { + "name": "cube", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-8, 0, 0], + "to": [8, 16, 0], + "autouv": 1, + "color": 6, + "origin": [0, 0, 0], + "faces": { + "north": { + "uv": [0, 0, 16, 16], + "texture": 1 + }, + "east": { + "uv": [0, 0, 0, 16], + "texture": 1 + }, + "south": { + "uv": [0, 0, 16, 16], + "texture": 1 + }, + "west": { + "uv": [0, 0, 0, 16], + "texture": 1 + }, + "up": { + "uv": [0, 0, 16, 0], + "texture": 1 + }, + "down": { + "uv": [0, 0, 16, 0], + "texture": 1 + } + }, + "type": "cube", + "uuid": "d2c3f2e6-8d85-8cb3-af2e-b53ed40f30d5" + }, + { + "name": "cube", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-1, 0, -1], + "to": [1, 2, 1], + "autouv": 1, + "color": 3, + "origin": [-1, 0, -1], + "faces": { + "north": { + "uv": [0, 0, 2, 2] + }, + "east": { + "uv": [0, 0, 2, 2] + }, + "south": { + "uv": [0, 0, 2, 2] + }, + "west": { + "uv": [0, 0, 2, 2] + }, + "up": { + "uv": [0, 0, 2, 2] + }, + "down": { + "uv": [0, 0, 2, 2] + } + }, + "type": "cube", + "uuid": "48341251-ab7f-67f0-6c40-e2e207cd3a36" + } + ], + "groups": [ + { + "uuid": "abd35d86-94ea-036d-dab7-e57f9c6e7e36", + "export": true, + "locked": false, + "origin": [0, 0, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "fire_0", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "267d4d3b-e413-f224-9a6a-b41ddb4fb781", + "export": true, + "locked": false, + "origin": [0, 0, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "fire_1", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "2ad7b1b1-de52-e47c-2176-832c809e6baf", + "export": true, + "locked": false, + "origin": [0, 1, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "hitbox", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + } + ], + "outliner": [ + { + "uuid": "abd35d86-94ea-036d-dab7-e57f9c6e7e36", + "isOpen": true, + "children": ["ee087d96-806e-3a44-4a38-ba3359e8df01"] + }, + { + "uuid": "267d4d3b-e413-f224-9a6a-b41ddb4fb781", + "isOpen": true, + "children": ["d2c3f2e6-8d85-8cb3-af2e-b53ed40f30d5"] + }, + { + "uuid": "2ad7b1b1-de52-e47c-2176-832c809e6baf", + "isOpen": true, + "children": ["48341251-ab7f-67f0-6c40-e2e207cd3a36"] + } + ], + "textures": [ + { + "name": "fire_0.png", + "path": "", + "folder": "block", + "namespace": "minecraft", + "id": "0", + "group": "", + "width": 16, + "height": 512, + "uv_width": 16, + "uv_height": 16, + "particle": false, + "use_as_default": false, + "layers_enabled": false, + "sync_to_project": "", + "render_mode": "default", + "render_sides": "auto", + "pbr_channel": "color", + "frame_time": 1, + "frame_order_type": "loop", + "frame_order": "", + "frame_interpolate": false, + "visible": true, + "internal": true, + "saved": false, + "uuid": "e5bbf92a-3b22-3fe0-1689-33beb377ef8c", + "source": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAIACAYAAACLuuzTAAAQAElEQVR4Aey9B5hdVb0+/K59ep1z5kxvmUkymcmk90ZIJyEJCSIdEQSVKoICIiqKisIFQSxYQEQFVEAgQEIJBAhIaCGBACG9TDLJTKa308/+fu+anJOZZBIwXr/n3vv89zNrl1XeVfb61bX2GQP/5vE/FOCZeTAZDu/dU7Mkfq4ESU+n9dsFqx1weIDlJ8F8eg7MFfNhLpdCSnIvfhFq8UqoYwKYKcBiV/AXG8iptMCZpWCawCkvHSp4BMBzi2A+txjmy2crM7fGiqwBVrjzLLD7DLhzDLB29HMY6TjWFhhggTvXgNVlwBmyy70TFodkUYDFhn4PSQVYK2tIRk2Em1No2xlHR20EkaYo3IVulMwdhCGnF+DNKy3my+co6cwhLA1g8yh4ix1Sm4IraKBggh/FsysQGl0MR9ALf/UCDPjCh6g8bz6KpmZh86+C5uov9gBpgK6GFMKNceSOzkbBtGK4S/Jg82bBHgwhb9bNMJMRhPfcA8PuQelpP0Fw5GgEhzh1MzRAqNKK0pNHIZVIoqu2GS0f1aL5/U3InfE4nAVfgn/Y73Dg1d+g6d2X0f7RH9HywTo0b4ocAgg3JbHjiXU4sL4Ve9d0omVLFDkTx0mNpTpTx6Zr4C4tR+P7Ldj0l3dRv7ZdBlXpNN2C7Bo32I3GzSnYZTyUpDnzhusMPPmq7kLe7DcQrPYi0mairTaFE+5PSS5AA3TuiWDu4yZOWWUiq8KORATY+dgfWBaJzrX6Wv/CeORMmomTlplYtNLEhz91my9+HqYGmPiLhM6U6HxHBsxEPGwiWFOCZHgz3r1+El45x8D2x9ch0rBV59vxQCFaNkcw9x/g2wfUwcPmm6jG/CSm5j8NVXr6VmV1V6kpv0mqWX8z1dTfpVTxKR/pnAO/tF9N/2OvLuDfOHQX/o3yPYN4OICmeyHfw+P7ez5qC8gTOMqkk2cXos/87w2UAVg2U5jHbJgk6eAABV+RAZKx3aeEPlTvMn3uMwDeXAV/kYInpGD3GnBmW+DKtsLqVDAMgJwJ/RySBKxYAJP0nkoC0U5Tz8rwgSRinUm4cmzIG+/HgBOdeOVcZT57ct/uaAC7B7q5FjvgkCYHK23IGelDYLAXjmwnsqoGo3TJaahYXIrC8Q6svc6WAdIAkTYg1iWzr9KJXCnoLfZKQQ8cOX6Exk2GYXMg2d0o5J2N4nlTERqZh+zBFt0hg+esEoX88QEoQyHaGhVu1InOXS3IHvd5hKY8i9yZL6Jlw1q0bdoh5L4VnbUt6NyXYtGeeRDrAva/1SLzO4z696No3xVHYGgxSIXM1fLuWbBnedC8sQM7l+9B44dhmKmeN6tb4M030HXAxPQHTKV0DODMLWFZHbInPoWys3fBV+JAuEXIuc4U6oVios7O/k/+6ZdgypFVZkUyZqJu1RrEW55HvPVF5kPdUzUIja3EghUmZv7yYrx9lUU3QQOMu/l2ZI24Hx0br4BhBRJRwJXnRteOP2L9DxZg9fkGdj+7CbHWFoRr70TD60+A3JvIGuD9n16PjT/zoXXDswjWhHDSUyYqL29GYOzf9MByMimLwoBzd8NV+g0kownpbptusQYgzddc26nKztqhBl1cr3ofE+5KqGn3pdTkXycz0dVXtyvD6tfPGoBNOd7wnwMgT6BYJyk/JZR6tBYe0QIWXPk5mKROV7aCU2jD6T9acfTMRCaztheWwnRnQxOUMyiFAwasLkBZcdQj0wKLoycP50BEhEe03ZTXZcIZsCBUZcebl1s0s+nJdeisAagPUQux2BRsLiXcyIJAhU0ktk2o0orA4CCKZw1A2Qwv1lxmyUhmwmgA6jypGOAvtSBbeIG30A5nyCHMxIlAdSEsHpd01gJXnh+F0woRGubWzAVyGBKw8lSYwSF2GNKCRCSFcFNcKxeBYdUoPWM7gqM/h65d9eja24pocyeiLZIu3WRZDZCQ2lu2xNBem0DT5oTQehK+cj/y5ryJeNsqdO18FYbdgtatEex9vQ0tW2NIxllcGsaL06/Q3WRi1l9NlRIxSY3MEQoyCbas2SiYvxZlp98FV8iCbiHnOY9BLXqhFzmz0PCLytD09lLTL+w8FTfRuHYXOrdcj/DeXyF64K+oX3UTsoflYPqdF2PnQ6UmGSxr0F2ovqAGeTNvEvrfK+9d6eZZXRa0ffw0PvrZNXj7uvNQt3oPEuGokPROdNe16DwZgB1PbMS2P16Fjh07EKj0YP4zJoZ/txvFSzeCTDwVl4uwwMGXNiHnBGEwChh97RJ07/2VaVB0TftDEp7iAArnXYGKLzyAaMNDaHx9Dj65y49gdRZmPJTClN8lsfF2L1m68MZu7Hh0OV46/0oYs0T2k7ArLqhT3kE/VI6c05Qz/wsqd/oqNfQbHUpqZbIONdd3qfF3JNQJf0jp6ymroPQYsC/HG/4zAKQN8oHnTxFpvUiktqj8R2thnxY8IxkpaB1eaBXfIRPMJsRlsR6tOA7xA4pvZQEooeNhYe2iqZkirQmSVWZohbw/zpRpAWtlTdRM3NkK3gIDVP0dwlSyKpwomOhF0XibBqJtkW5TBoBWikdEXFaZBZ58C5yiXDhDNvjLvbD77TJD7fAUOpE/1oOcKis4RgQxeHpGDCl/sQVWB3oUzc4U4t0p+AeFUHTypfAPqRTy7hYyjiIRSSAhdgW1WZbVAOx3x/4kOkXtb92dQldjSmpziGr/PFKRRkQb60HaaxOp3bA+grbdSVGLGYOeQWTN4RZg3uNQ5A2anIMuWNzD4B9+L/Jm3ID8qeO17tTdDFCTxcFDt0ApYNB8N7bdm2t6cxRI3q2b29C05mS0f3wZYi3r0L55IwKD3Rj11TJs+KHL7DMG5fOE+0wZJ+zbIrX0AECO1g3vYvN99+GDO+5Dw9pmARaSNBSSsRQMXTV6urD/nQ7UrXob4foOGXU75v79NYy7PYZBXz0AMpdoh7D4ODDg81ej5LQ3xbYyMOTMIt1ig9bpzIdTcOe7EBozFCULT0F4z0Ni4pyITXcHEBzqx5zHTJxwfxK7Hvs53ruhFO27oqh/qx6DvnJAGVQoGl+fh47aLtgCxQiOewT+mt8gd8ZqVH29VesJLe+cKq+3Hc4cD8b/LA6O/2QR95DDOHkFVO70F9W42+IqNGmZ6u/InrhMGdYsNejLDTp52r09toKU7xkD3hxvODiWRxZfJiL9aVG+Ka2PTD0U0y/A8vkwnT6IlAZszkOZ+7sz+otMiqTSkseEnherzhQleyH585G5MwDkB09Jk3ll7W6tHyjNWHwlFuQNt+G1LxmZGZiGygAwwh0EfPkK7hwDTjHCnWIzeItscGRZhaSt8BZZkTfMhtUXKGkbSxycibylSkN9kO84KZpqKmHCV+pC3uRqeAcEERfbIdGdkvkgZeWPZRgMnhjCrSYiLSY6603w3hWyIn/6XCiLFYmuCESrREddEk1bEujYfwghA7DwOagFMqnoZCF3sgek6flTkH/Su8geO0WmdA5I9iTltGRmxRmAt660mOtutJvPL5a6hOg6xYPR+v4DIuLmIhluRaRRCK3Mjg9vcZtUc1iYQQO88w2rmTs2RwbKBlpp5FApGYPWj3aKDHwFm/60Bk0fdwuyCavHCsOGjBGmAVq3J9D0YRNi7XH4S6yYdNMcTP5NElXXfIRERMak2QT5YP7UauRNmwub24LymS7tU9EAY66bL9qHDVmDgyg4YTBM4Wv7VozCll+PRGCIW2vvk+96WJSOzdj6l2Xoqk+gdXsUk3+VVAb70b7lA6k9Ad/gGhQt+VhspNUoXPg+qr/RjqHf7EDTP08SXekDuHLdmHB3Qr+RjPUuRoqZd+KliDQn5XW1Eq9PaHnnNCQjHTjw2v0YLArG9vsLZJwMbP1djvn6RYZpKDm8A7+vpgqNF568Tp76/mVPfELlz31TDbyox46gPTHpl0k1+JJGRTeI7kKfKv/Fh6MCkKgosZYJXzgW5lEBOBuVEnJ2AytO7p+UCdwvAGumtHZopqLgE0nNAaMdwUK9Qx8AKhfPL4HpIi/IUnCKaPfkGfrqkHtfoQUEol2RBskAUFRZnYBhkdd80Kz1FFhFOw2IoHVqAcPpTSWEouAIgFg3EOuE6MI9V0eWgdCoIq0XpOIpcEy6DqTQVptCV1O6uFSYvl36CtTiF6F4TQk12v0WOPNLkT/7OmRVFQlzcUrrFBYK2TNPulymC9RY2T8OIGsLH0igc8cWtLx3L8ykzNLuBKj2vPU1i/nSGYextFe/oMycGifIA+1ejgE09bVuakbt85ux45mdaN0Rg5Lq2DK7J13/wS50ienfsTcqcz6lX9nwLxZgwq2/QtnSuYh3SZ8bTVClCQ7NQvZwoQVx0rx5hUUbYQaxBi8JCue1wCtu0dwx2cI0XCKdb8P+Va+Id8+BGb/9L4y4bCo6dnei7tU9iLSm0C1q0IJndKMgylNElAcTwRGDQJ2gVOyksnN2YdiNXRjx/TDaN/4NUAquHAdGXP99kGPN/rupIIdBcs6dNAJx0cxS8Zi873qJPvTXsvZ0JLs70bFts+YP+567Gw6xZtdeb9Pebt2FvNmvanvA5s9G4+pTM6W3/jaEvc+twKaHt6Bta4toa49KRVHhnRa0706IYxJK8wPD4lI88ues0bTPe4bKy5rViO+GlWgoauytceXMPVP12Axx7WNkTboFvDne8KkAx80PyFBo0ZOs6RZ88TSYnKWHt/SIFtBmeFYYCEW8Q+wFt2juTiEsp0hrr0huglENSAP1AeAiBKUO5A0rSfHkGggMdMCdSxrvKUILnyZBzxP6KlmLVkKR2uIRCOtWImjcsHqtoO5M11dEJHhng6kpsl+AdCQtFbvMd1euX5TPkfAN8EorrGDLaOqh12Gk79nvF0Sf5PPSV6GibSmED7Sja9c2QCmQG7lDCrSZqd3i4KEBaMIEB1ngzjbAkWcaqa99ezf2vXEAda+1oHNfEoZ4s8ipHD7m6AkaYMFyqEhLCuynJ1dhw49c5tAvjUTexHxhcyY6hdzj3VR5bEKdLk0Lq87qYSoGcd79ptV0CIG4c63IHuoUv4lTHJK1aN3UCJ+I+zFXVmPQkjyhWlEDRE+IC/8kIMtqACpVylDIFlfn8Bu7tYJdeVkTRv84Cqr9iXAYVrcTTjHCKpYM0uNBVUcDdO/5pZkzKiRGhCljpRBrepzxmdD0xgKkYjGpvQMjbhLesG0f7F4lLsKDXXAVX4nC+Tdi1A03iOpiRdNbN2cKiwmEPc+9gh3L94sftRPNby5GMpoUDUUhnHbChGt/Jpz3d/AMugWlZ+7QisXmXwbBYLHbUPtGFFwFUvIG2je9h+79MVANDoh9yZoMd9m1SjwVqvdRdVWrYqi4cJ865SXotYQxt8QUnyeJWkP/Aa8agKd/J+i3cCwA2gxU//sjZZbrF4BMhJT5nKj4rgBAP5NLJPYLIrl7T+N+AZbNgGkILCWwS3iBT2xqXpXEKQu0ShZqiwAAEABJREFUusuC6WCkb9JXEhIpzu5RehbavBYomWTUUaKd6GP2sswRAIxksLml6eLRCwzJhqfAJpJLidBkSt/QB4ADlk7W870jjmhzF5TMAcY7swBSLu/TIQPAdURXEOAYMDEuOnJ7bRwH3u9Ew/sRdDelYLEqOEX14VthHoYMQCJsalrwhIC3xG9ecVIWgpVO0G6m9GaLXMIjafY4hXLTfEMDvHKeMjld6YgNVFhFiNoQl+aHG2Lw5huoPMWHkqlOccaZ6NiTAKk3mYA+NADvLLLKGxruw7g74hjxvbCWzOPvkvtrvy16kk3koR2ubAvyx3nAwqfIFGc5Y+u9uWZ2lUNG2ITFbkHn5usYnwmd258XTpUSkk5h9E/qdMv4itODaZSfuwpFc2Zg8NljpJBC6wdPyLXnb9vvc8Wv8AH2vNaG7oYo6p6chFTSBNXBRLQnj7FvxVKE67Zqt+fgSxtRcvpWLspqV2C8UwqtjemcVPU6dtQLUAJ0kXhyZF5IilG3epc4E3ajc+u35bHnLxVPYvuzHdixsgN2F0BtpG1XEs2fhKWrwLjvXYEJP74RVE6MSaL7j78jrnyVt6r0QT9iWkqd9BR0VfOehKJ9wLUGf82vlHfwLTq70VPn8Z+PCUDfAWcd9WhKLor8w6s6KgALO2Xue0XQOGX6krwtNmTsxTTQUQFsMnjePAN2Wf03LD3ZKbnTE6gnBn3FezqSVwI4gxb4Sh0ytS3g5EE/x1FbwIlCqzXRnYQhVKgkJ8dh2WE2lET3wDKRA9bzBBCgUzx8dMQ3b42DixaGFbJkks7Rc80AUH1lX2n2UHsvGmuDV0wcrnScJHOAWgsHk2oP30pP8YNjwEK6z6JUZRUboo1YQJuBmrpLlApK77yhFrCScLMQVjJd/CAAm2ZzKpAqp96XFJLuwtj/imHq75MYct4YEfc2OIJWzY0CA60gLeDgYVDvD5RboCwQEW5B0xvzoR8g49D1PhIdbVDClZUBVH5RHEwpgK2VZP1nlMwZiMITSlE6O0cTSvuWDVCCluh4EzsemIX6NbvQsC6MaEsCzWvX6EJ0hegbORktH+1BMhyRpYB7UPOtThQvuVfcgFnYfM9chBu6sX9DAgnx6lAj6dzbhUhTUmwogG9NysNo+CCC5g2NsiSwis+yMLtIBtDErpe7tGhXCuBbaK9LoW1ngvIFVecOxMhLa3Bg9SzTmP1ICnmTSvHJb34P8QloZ0Plpe+Aam7BSCuySg3s+HORSd2RSibdZF21B9D43ja8cdPLMJQcXGekvK+8tEnlnLBSWd3Vas6jphp/Z89aQsUX69TC56Eo8shcxKuhRt0c1Tamodv9KafDp2/v7McE4DIBDW2nD/iX9APWQH5AVZ9UyIkGGUzGHx6O2gKbUwhHGImnwKLNf1k9P7ysfj4qAKUPpyyVbHIirjn2NxZHBeAKICVye20SbXtSiHUBBOqtArAJfQDYb4p3ejFoyZN8ox0AXccEtIvS4QqKCjBTzyeWRwaAo+zwQHs0PTmGcCFoqnPKeutq8WCSR7AEW3KoOA4BUKUJDrJi9HWnYvhV52LkDT/AqOvORfmCHOEPVj2QDtELaHhRj8LBw6CUpXbC/tHM6d67EbbgSKGJSbA4syETVaS2gsWhUDo3X1qm+rB2o2CsAwXjvSgY69It695TDzPRgci+Zdj77ANofL8ZzZvjiIlx3rGzFeQLVjsyh9G1Pw4lSlTJ4jO0fZA/62zs/sdd2Pno/ejcE8aBT5KIibUSkyWC7vo4oqKl04pLIxgtO1Jo296FZKRVx/lr7oFIXex5I4J96xJaG+FbICV2iN3ETANmebDxTp+54ccu0xjz9WEIVPqw9cHloH3Q8NJkFJ20VAQJEChT8OUprP+ewySTPUm4c1JWQ+n57KqLgJa90bGtVtSWGAqnlyFv+rnY8/x7aHn/ZUBBVDsTk++8G95SHwKlCu0fX25WnV2B+vUxtO1KaJXQ4F4CsZNU2Zk7lH/oL9S42+NqoNgJ3Ky0QHwk7pKr1OCvNqrpfzKVdE+Rd9DKI7/g68xMJBzl4AQ7fPr2znpMAEogTl/Okd6Fet8fFYCU55SZ5woZ2tDsT7kg0FEB6C/T71tObIFmKixxWDgqAPOFZdLw/XeK6bvoeb4XxvYN/QJw0OjyYP85iRaLl4/FyCOPafKwIInLLRKZxCOt1/7UlafCfH4JTKUgijahDoVMC4jOmVd1VhEqz6hA1XnDUXX2AJRMdgo5G3AFFOxeyPVQYd4ZPPF1kcIcfkOU6jjcxZVwl4yGI5QvEtsKq0vpUDDapcmaZdLBoEeC6yYhWQaFtDHS2I2UrNpGm7ai8e0P0bqlG+SLNEi4scGwAGR9GQDuBLK6DZTMHYYJP48jZ8JI1L/2DvauXIsOWaRo2pYSqwV6r1ZY/O/RTlOoNV0cME5aBtXDE6w6Nm/2G5LBFFKOYcpvU9p25luY97jkk9fJTIWjrXjnGqtJS8cgqdKs2/XMemjv3bKhCI0sB5UIjj7fyusXGyYLUtGklE4JScdlxWfmQ6Yyoq0J6bOJ4BCfDF4B9r+2Fa2f1IKsi6reiK8Mhb/MDvLNnQ+WmGUnetCyPYn2vSliwiDLCo0qRlbNUOxbvUW0Urtwoy5M/snleveT4XSh7u2ItEih4Z39IPvjrqicalsPAAUGaZy+xPFiNwz7dreaLzYCaV/JUbjgPbVgOdT0B1Jq4t0JNfTaTolVinmJoOcBb/oLy2aiXw9e77zHBKCkcmYdUqh6F0zfHxOAmaS9sPR0l49HhGMC0NznxpW03XREaYk4KgA9GKSPUw5aqJK3378jADjPqUTSuIQCnjo4kJ+JpdHdWT7LhfI5PpSfFJCrB/kjLKCRSTFPrZ5cGr2OTAvoS6Xv1GI34B2QB19FKdyFWWJ0W2BzK9glZA+2QLesNwC50GuylhoYYIDTN94ZR0rWE+Id7Wjb3CQCNo4uWdmg9yreZcJi7VVabg1qn1RrC6flYOq9SQRrCtD8QZ2Yw3uFD8TQssuErJQhKmQcFS8nl1KkXObP4F1EnJFWt0v7zunVh9DegY8SOFHE2RJZOiGLP1lWQ7tbmBugukNS5kzVHMkpS0D7XtuDnQ9/BUJx8Jb5RBMByCfZxfT60pKXoSil+XZYCYGNRLSHw7jzbbDYLDjwbj3ad7Tr8WB9g072wi/OKIJ88AOnmT/Cik5ZtO2QxV2mG5TC/gq31BoQ875NM82mT+IY/fUJWPSCCe+AXLTuTMIqOlLH3hicQRsWSnxOpe49jFS8xcyqqkDFhftQef5SlJ+2AP5SC2xZBdp+4mrH1LtuwMy/pkAjbPj3usWiCWDY1VeR9YnbzBZURYs+UDyyJzyuQpOfVtycEJr0tMqZ9gKj+/gWGFF9dZvyV/+ct3zz7En/gdN6uRhq1F77z4FDimZ/GZQCDOnqcZMzJ9nJz0IvofVXAeMEn5fjD0cFOBr5Hl5VHwA62LgP8d1rbWbxRDsofThtuQn6cL0gDdQHwCkmjk1cHv5yD/wDs+ApdoLTnHaT3QNQEHNqpwvzqgEowl46XZlKJC+/YaBikYwIGYs2yjU1Oh8o0mh0Hq4raQCH1Jwv2vq4718t7n8P2rd3oumjdnTsTWLW30y18DmoaBdASb7oBU1KrFwHDUBnoz3LgURnLcq/8GeZokDTlpR2gelcciJz5SuVW3C7Gdkb7w32ye4GDqxvw74Xn8Wuv14IlywDcBIxA8Phb4TdSE8ug+urbJRdBi8ZS+qmd8ripZK2kWG8/XWr6StQYI1vXGLoDZ7hVmTcw8ZS4TjufCvceQ7hfzGw/e0iumvOLcSSl00Eq/2ItJigIRoTtuaRvIue3aXfCFtn1D422AwOzQGdD2ULh6BgagF8RQYcubniH5iptwyMve4EzH3CxIwHUxh27f3Y9MthqDp/FBrfWGAapadvVe3bmhHe83MUL90Ib0U1Jt/TiW2PfYhEeyMrgS1Qpp2UH/+XF7WPXy1Mx4qCBesQmvJsDzWO/lFUuUuvUTxyp69ShsWt1xSKDn6vEBzzsKr6Wqsa9q0uJWsveu2BeRlkqHQlRz1xII+aKAmfCsBBlnxH/ftUgKOWPJjw3w/AJbDXLlTmP79smKvPV1pL771AebDizKVPC6hUOkUr9w+ww1/ukJVwK1yyNEJdibyC6Tjs0ACsgUqFYZOJmASUocCFu0hLEnQHUqCSxBlw2KEBXKKJ5dZYUX3eQKnVhq59MbRui6KrPoV5T0CREknGosQfVhzQANxK6wjYYNjsKJozTWoHWkSs0xnduwSFK5+p9vDKoAEsDimwNYKm93ag/vU3xTIxcKz3b7EDFDoZAN5YZH0h1plE65YIuhqSmQzkg2QgnJEvng7zhaUw2Z10a3QLXLKm7MiyoPtAErTOu5tMDFrggSlHSBYwE0LlJGfyRV+hgX3PjTUJyoqN975tN4ND3Ki84EIUTc1GqMYFb4EBd74f+5aP1NuOh32xFNN/cR2m//YvGHzeLBx462MMWhTCR7d6TGPsT2Mq3BgVF0Ct0H4jAtXFGHb5UlmorUcqLlVLNf7Kcdi7/HfYev8lYke9DbvPjkGXNGoeortAtSV6YBe23JONfa/vQNvGt0DnbGjiNWh+ewlMcWlVXd2GYTd06U0MVde0CWzPnwYYf0dcrzkOuaJFTRAfIv2HSg5X8aWKekJo8jPy1P+fBujBOr7z/0AA8n/KSireNLgpeI7VuT5dIFWSfP0lFmSVWcFJ4woCaQ19maj+h4MZvSMy4krWEyitEt0mSIGLD/oPVO/MB+81AGugxl4+2wO6/2kjd4hk7mo0tS/xYF5Qb07fp68agIyC9GD3O5A7Lg98pv84LY3Tmfu7agA2vaMuibat7Wj5pEmrtf1l7i9OA+gE6SDtgfZdcYRlEULHyYnOiTTta+19DvV0STj4pwEcsppv9yi9jsKFGRoYVLRiLS+YOXRMSGaCGBbAl6/w8R1ek29MomGQjXPVonTeAOSOcOjXx8UpbvCuW34Rqr7yVVnx9GPMlZUYe814lJ9cJAv4UQw4waF3ixocrEQ4BWUYGHjuNxEcGgA//mr6uEviFHxDf43skTVo37wXDW9+iPbtTXBm2zDy5gjEIIfuApsda23H7sfvRsumVuEN3Zgmay3BsaehYdVUAbKgRkh5xE1hvYlh2Le7kD4Mqi20AwoX3AjDZoALsrYsj053FizF/lffQ9ao67DrwRIkOtaga8fNOo2nA6tnwuB3i0oO6gfV17Sryb9KqgFn75IYpeyB2WrUD6PKETpVlZ+/V9n8U5V34A90Gk95M15VugtEO97wnwGgXshJw3f/aS07ogXUzP2FClnF8gpl0pA/HAvkCADONkopQ0iaawu0mT8TAP2H1Epdog9ExYtNg7u7BaBk/kwAThFvzmyrOKRcgAnQRfZphQmc6QIpkD61zrooDCuTPlvIAFA6RVpT6BS+QAPjsyTRJy0AABAASURBVBVHDy3QHqJtTGWaK5vkg1wi2btsqEmFKw1GA5Sc+q0rLdLJnljdAq6n5Y9zIzjQCpKyOxvwFlrRubMOFUuHgBuhP77daw49M4iSqR5QBSANkZcaAMDm2zw2lJxUg2CVC0WTvWLuxGE4rCg+9RPkjCkBPfqduzsRaY6Jj9WK4VdfifHXjevpQiIs7Ft8Jwfe3qSZhbIonPDHFIIjxmHvk9Wg7jTkq7dizK0xjL0thuqvPwhf9d0IjLkOBh0LNO3zpkyAUBjIG5y5Pt1BZ8FkNK3fCWdBJepX3Y7u2p8JOf8QjpwzdHr9S9+CwQ+lw3vuRs6JL2PE98OY8rskXAVFOoNn4M0Y+YMIdj3xHLY8Xoe1370OnoqbdNq+5SOQ6A7DkFrFVrial0woOOndzD1vxt4WV5xYJ/5ZfNOMkFC0+EM16OKG/4n8gDyA+444uP0p13oAep30POj1DIsNYlQpkKQpI/EpRwaA05mmvlPW3/kqSQ/0Xn1KeWQAXGInOLMN7QJizTS4P60w0zMAZCJRoUbaCP/Ku8kAcGtApN1El/jP6Usl+mcJGQCLFYiLxCIpL1kF9ZJo5h/+xG3ybfQGIsc+Yr8yNbLsIVaxmRVcAfEjL4TpybfIAl4SpTP8WHOpxaQ/hYo5l9P5pl4SjweBDZ6UoUB1v2BSEIGBNuTW2BBpScHmtWLwV99GzmhBVUBc7Ilk1BRytqDyzAq9EdIgAF9bMpIS0d2uM3ErGT8IzBpSht2PzILVZceAU6ZgzA+fxaRfJzDk4vNResY2ZI8aCIO634z7HkL2iHzNjQnmzncTV8h4ENq3NsPq9aJ9y0Yh5T9yxU9/2swM7VtrYdDJEK57FgPOq8W4O+KakXjLBzAd2ZOexqgfRdDw1k7sfL4RH/367/BV3a7T6p4ehlircPC3rrRi74rHUScrGzpFTr4hp8gZSEbFCHthPKKtSQQqrFDS4YaXZ+s0cQ1gpGgpxuRfJ9Xw73Qr4X0qffA7R95bnQNVwfy1aurvU7KekFDT7k2pgnlvMykTBFMDHvepXwBq6BTvHOBPQ+4XwOoErA7AMD6tuOTpnYW6AY1winSusdMh2Tu9v/tMHVRp3UEFT57S8yFtmfZXqHdcBoCbe/nzFfSrQTB6ZzrWfQaAzeVeA36av3jlZ4fIAJCZcq9J2jqhx2LNpYbJt3F4CyhU03EagJmoVFHNYUHSPMfCsCkUjbWBy2Svnq9MrrlxM4NNSIVlCKIBSN/OgIGcYQ7R1g0Eyw0kwhAb2YLSxTOQO9wJm0sGxoQ+aBaVz3aDP6qiAbgoR40sfCAuBrcpvMHA6OtOEb9qAE1r3xFqtKPwhEJUXzwXU371FgadMVrb0aEadw9XHnPFEGQNdIPcmH5TT4ET2ROXwZmXg+593SIjLIg2dyDR1YK2Dd+H0IduSbQlBiPa9LRpcXkw6MuPYspvkyAj8VcW6wykOOoErVvasff1Dmx7ZC0cOSMQ2X8/ah8ZiIhQqbHma0vQuPYTNK35li7EU1bNQXKObMO+FaMR60iJe1jJ4g3QsXmFMJqLkD/vHky44w0YMx82Sc7Yv3ojdvyxAN07fwzvkB6moSwe7HxqA6g3TpUFHH4kWbhoA7hvyx5cIGMzqWcMSNzUAQZeVK88Fd/jow4We6GiPTHtvpR+Tp/S6w581m+BzT7e0C/AU2Jkkyd8FtA+AGQgVCaXvAJF2viXAehTc2d/lmKH8vRpARkJJ9Kh5E+/6wNAtx9XeD+92KEcfQAOd8AdLpkPFTt0lwGgb4xqTjpp5akwHWKUU2snr2Q6AemM6/2GNABHnqsb2QMN0Bin/KfC4cgyUDgtF7TgHaI7UfGyCI/w5CpwVyEZiwbgjhZSIhcglIKe90NOL4S31ImuPW2y6mlF3mgPKhYXYcTXZqB8QT6GXLgU2YOMnqnMXT2+Ique8+I2gyffhuCouXDmeEVPSEBZlcjJJAyLMJrOZr0uFxj7MJjX2PlQiekp8mPQ+efhxL/IqsajKWQNCcGWPRIDL9qPCXfFhSfE0LA+gj2r9oqu4EPr+vOw44Ey7bA1Pnl4Dzp2torsf0tb5xzEwIhZcJdeq79l2PN4JeLdJgwbtCkQbtiDwOiHkDvldAw5exAMvneK6fo3t2HHg4vF/XeqZHiQOMKBtqL2he36fubDKd3CsrN2anL2iWOi5LQtPWPw6nkGsmtyIa5/NL27Gtvvy0Mqtgcbf/ld+Eoc4O8jaBQ51T1Vg+2PrMInd/rBH1rRb2GmMBX6B5Qc9CnyS2qLo1R0grga8b2wxB76K166Uel9CN/sUDMeNJUGEODj/vvvBeDMSkucz9qkPi3g9GX4rIWZrw8AdYIloicz4bOGPgCHF6LEPjzu8OcMwFMzyf0PJXMsnH5g5WkwCUR+Sandm5SZOwPAzCRlGlrUk5SC3h2cN9IJkrk7ANhdABUw8geSfB8A6iSU0HQ+uAIKZdNdoAUf70hoaR2qsqFkmhtDPpeL0hM8qFiUDzIXgyhvfNUw3TlyawK05N25BrKqC+EMORDvSsEQYxzSJKvHDsNhQ9nnr0Rw5CwoKWK8e63N9Jc7MfC04ZjzDxOzH3odgSE+uIsqMfS6DtRc8SUthZs3x9Cwrl2o0obObSux/5XlsgIKGPSrR1viiLe3CUn/UBhHHYIjRiM09Tnw91Ca166QOFO3jGQdb+/S+kH2iKEomezoocayJTPQuL4OtU/cgZZ3fyreu++yZ4i3bkHdP+v1/dS7bpH11xT4/WPDqmnwD/+yrMdM6QH44BcvwVfm1a7/9s3bsfvvZ6Fj09XY8dhyeIvsmP6nFNzlN2qgfc+MQO2z72DrH67CujtfgUF+OPuRFIrmXy6MYgHcxblo/rgNG372S7RuTwh7y9UFedr/7GjE2lpB26lV1mLmPSmcasR3e+id3yPkTHtelcoCJul9mtgGcx4zVfl5tSp9FC58X5V/YY+a8tuUmv6nHl+CvAhiH3/4fwAyE481fCRfsrlj5ckMIjPTatG0P6OHN1DlCVVaQNKl6GcepjOkgTMASkk9JmCxQ1vw9Njxc20zYWq+ECw3UDDSigHTHWICWFE61SEF0DOVXzgVpkt4gI6RE79z9Fe44QhateeOPMIiq4GOgFXiHCieNwLBmkKQOxn0HQTFrB0wLwRumZv43dnIGuSAtywXY34S1e5AUmFbbRItW6Mi6g1EDjSgZeM+UBXUm3noE4ACmt86BTZfkVjy5ShY8LDQxnxRMOpBzY0h3mUiGUlApjP8g0Kg9aLHIGdUEC2ftGLfS6vQtvE1eAfP1Ip0rHUfDggTIecZfdUYzXCqrt4FClj/kLGitfh6xmD7ika4cuwYeP4P0VXbhP2r/qqXBepe/kS0FStoQxQseE9GB9j39BTs/+dW7H7qBWxd3g6D/JBkWTBjOprf/T3sAaf0rwOb/vwm2nYl4Cv364I87X9+HLr2NiDcmES7rMWMvWYkDG5qb//oEnRs/xDeQVMgol27OaY/kMKUO+/UHIiF9y6rxs4n12Pbilbw2/f8iX4Zj27o30PJGv57VSHrB4FRf1K9D/fBPQmMKzl1k+YDC5+FWrQSqvrrbar081s5PMQ//mAcf9Gekv/XAWiI89dYjrXK0WcMqANwaKgbcM3dHVJQFpK3wstnK5Nzny4Brk1yhwTzZgBYi1LAU6Jo0BXiKxHSFXWf0prkbHUquIIWuHJtKJySjUCli+V7aIFmfMkUJ6bfeR6GfzEfWQOs8JV6MPTS81B8QhZoS3UdSKFjX1KksxIVOIaufdFDALyzuq3o3v2euMULhFmEkDv1JHRuf0tEWRTc3EsXAflCKmaiaMGF8BY79Q4hg4V9pTa07wzjwDvb0bl7DzxlFbD6ykXkd6BlcwTKUKj6fAgnPWWi4pwL0fTOY0Jk+cgeZOnpwr61Mdh9BvKn1SDc0IWmtRuEMv8mvKABrpAFs8WGGHxpI5LdG9CyfgWaPmiQRf5dmCx+OIN6zsnPmsibWC68oBYWhwUtW7qx45latNcm4C1xsZE6NLx8Ljp3NaGrPgmu0XKvsxHtFCaxfKR4KNqk6aWoub4TXD4kExlz/RLwN1FYevffy7Fr+UbsXt2Njn0mqHQx3uBa0rpfbhCzpkO8E4MYlwnRxh1473o71t/oEF4ZEBVPYcotZ2HRShNDv/E4dr0W7RkDbqunXZA9/jHV+yhatEF/zzDmpzFVtOh9xd9SDI77u87iyF782b9nyjSpnxujn7h/Kep/AQCJ7Fh9OmoXqJFzXc0i0vr5xTCpxa88FSb5Q9qKJ3C/AMzszTfgFItdKFwoEHrLsSvbEEllIH+0E4FyK3gYPNE3QH1g+wOF5gc3O01/iQFfiQ3li8qQN9Kh9WQumYTFYW/YFGgWxNpTLNozkdhMe5YFqZjM/dIsBKs8CI0sQ7yjG8lYCtzEwx1AXHvgfc6YAcJYhFUJhCEBbFr3/gRaN7UgfKAT7sKgkHNAGEdUE5SSXO/f5DBP+PnVKJlXja499cIP3KADU5KApq0pWJwKWYOzQNW/bVMD2jZtEarsEmeEgUm3XKz96OxL9959aNvWhcYNHZj7OIgNTLttKULDs4T7RHRM644o9qxuA3+2wVNggyN/DhuK1g3PoGN3B/jxaFdDCnSV6ha0rHtd+p+EuygLVZffDkpmavBDL6gGtwykovu1p2/vqp3Y925ML+T4ii0wZBgMQm/6hzCJ/WHxYBbAVXwVo3RQkmPdtx3Y9JsbZCBT0jqFmvNLMPXWpaj43Fho6/2NSwxz4fPCKGePRrytRRdMn7wDT8DAc8/D6FuiGPjlBnB5hAsZ2ROe1N5N5svsP+C6Ab9jUL2OrOG/U4GRf+wVc+iWPkYNwNO/E/QY/B8FoKSmdk6tnDpxWkOnyGdcutv9jgG3yXhCgMMHKMmhic0Nkc4K/Dgwp8qCV85TJuSQZIC1UR9YLwRDL52/QMFXaEHxZI+Wf5IPdFbGRFe2iNZO0GSUsYDBC/fdcbXT6rTAV+ZEYJBdSNoHky4+ANQRlrwMxVUQ3mdVeITIlKSgB8DugXjtUujcExUekIArzyXk7BJNNAXuFGSNb15uMUddUoH8iUFxlcfgzrMeApj7D+mqBVLQhlh7Ap21Xejc3YqOPTEZBwMjLh4kK32Pwp6dKxVERbmIo21n/BDAlt+GzMBgh9SYBFtNqVz/XhjUSty5FvHs1cBMxdFduwv8KJCt4hZEvhk9BuH6LmmCgjvfhYrTT8BM8dxN/cUdGLQ4B0O/dhtMM4Hdj1yif96l4cME+CNTrmwFIdaeMdi1OiKsLC7knIXcE18BD3fpN2EP+PDJr7+F3U++KE2PgQM4YJYbIy8qQvHULHBBx1gpvH7xiybyJhTIcJvofXhKh4qBNU5vXBj81b9rt+Cwb3eh/It7wV99Z15jzLXzeEX+3B/pRUv9cPCUPXk58uas0U/27MX6mj6N/eFtWPcdu2kMBeCvAAAPFUlEQVTknLBS8XAVfImXzxw8ZdepMbfElB7ENOrxXP8vAyyfjz4LdeQJdNKt/BzMV85Rmd9RzIwBRTpVeEobKp/ePIW8GiuYmVOWdjKVbqtDaXHPSQU5MgBumZoOUe/9pVZkDbAgq8IOTftWyXVwfnHmkVY8BVYhMiUJ6JnKdC6QWYSbUkhGTbhCNthl4Z56QKTVBF82Gc6HP3WbOTUOrR+QFoigW0DZT+vd7lPiR09puuhuiKGrIQm7R2HwQh+GfnkKPIVZujB3BnTWp1i+pwXaJVhilUQhhyREF06icWMc4RYTzqABb3kerO5sRFu7esDF+Ai36vI9ANw6YJHBceVYUTKrEOICw6grRovn0o2KU8dIFwzxH76MA+s70LglhfnPQDk8vQD43T83b5CVFcz/GWItz6Hg5HVw5Xux54X1YhvsEMUjJuoOkD/CCv4ga+4wm0bQY9C+8SozNMwLi7g7HblnweodpxPdRUXInVCM8T+Lo/yMU0ETgAsW1d94DR17EjqPQXbmq74bhfPOEdO/oSfSlquvBQvWgesJfAiOe4QXHayecaj58lTwzRh7XmnWkf6a3+rrsU4f3erBll8FsfY6O6JN+3WLDH5moj7jMfzb3WrI11rV+DviqvSMbbqUHoNj1fppaf/LALikRsOcP7yU7lqfLpDF06NH+U+S5v4kqvrpzFxSszkh8yUdg56pzEcWps7sLzaQVaLgL7GAHwkbdqb2DS6hDyoajM20gNvrSdJkFE4x8+1eSRKC41YKZtQmwdcsZqDcAlIuVwchh+SS88E/qwN6OYy7hiOyLB5uS4FN5v9bGHRKjpjBTiiLkLwoGmHhEyymAaiueHIVyG1oD1CR5m8CRNoA1uQt84ic9AuzSYoekdRkrnmIIGgAuYL7C9i3/LEejLtxASqXBlEwyoaiaSEYVguaN+xF86YoWneZWPg8FNUiltMA/Go41iHMQzx6eSdMF+aRi+JF14pR4ULThy0SWhFpSujuBQb0rHYG5ZoB2PFAoZk10A6b8MHQlBWw50yAe8CNwg8C4OdIY374OErmDcaJ97+iTYGqL5+DqFSoAThA5RfUoWjWeFn6+C7jROX/mr7ya0v+FwR79hK90dHmn6HjA6P/gsFLCsH5YjRvievI3Fmvw112PZKRLfq5vxOXCDf/IoD133HIgJuY9YfbYPBDp96Zd//txN6PmfvaRweKndSJRHccZafM1euuqy/7Fgx12DHwS/sPi+l5LDtzh5r+gKmGCU+QcdKRJ68ARUamkuO60a/xuEoeLPTfC0ApfBBYvyISUO84ptEEoCzlPUOmBWQUnhBA857ucl++gs2tQAJjxnRQCiKZ009ABoBERJLmsDoDhsxKBWamhg45qGBQDvgKFQyhyLRj4hCACVisEPFlgj70eKepPxC2OqF/xbV0mgO+YiuoMyTEIbfwOSjIoQGI5goAgqEldHezibY6E7FOaa5XCR+wwZXjlNkHiTNBMpey+k8D0OHI/jpFQ6GLq/rMPFmAsCNUaYAfBFjshnj7utAmrvLZfzcVjQ9dWk4agL+4wQ2/5Ik544rgKshH4czRQs52EaIxtO2IItycBPdsUcmiHpVmthpg3Y120yfWuN1vRXDUqXDmD4G/5gK4cl3IKneg8pyJKJwcxITvnYK5j5uoPKMS6eVlgyNbfsYZKJhagsJZU+DIPRHB8Y/BVXQ5SMrDbuwGFe4BZz8Cf813kIzuQPHnNqH0RLd0ADBoeQRGP4iys3ciZ/oqMfO7dcLhJ1tgDrbddxK23DNKk7PVaZXnPNM4+TmO/aHsDS9/79BDr7u9y4Zqcg4fiCI0ugRFCy7Axw83wKCvsFc+UW3+0vsxc1+8dKO4STzgwo2IdviqfwEuJxv0Fapehz1req+nvrf8HbXeMfQh6LeQqeY4bv6zAHSTf1qj+rSAEpfinbRBT57d03/xfvkBs1IykyLpxbOLjqz6wAM0Cag3kHaYn6FPFmURck4AiaiJRMQE9/GzG/SZ0V3kKzRgdSqZbMgcGYB0s1ICQHKd9wT0v5azSze8hRa4RY9mBSQ6Ctc0ggZYNhOmzQVhVQqBMgNlsqbIFTAuSgQHWnSt3fy55P0pHP57EBpg6StQNGecAYXsGg/4Szz5E3PAmiOtKe2Ui4hCwe2XbCkHuk8LuPRBBYMmT9aQcvEnFsA3uAouEffcxFB8Yrbeuzj8ojLRDUxUzM/SbhOCGPy1idI5hcgf50fuuGK4S0ajcPEG8H8P8NeNx94Ww+BLGjHg819EcPSp6Np+E0qXfgtFY6wsD2PRSqjQxDMhOjDyZ/8EhitHJxx+8lbdir0r/ohdj94p3r3vw+6zgF+dGF07fmT6qu7S+R1556Ltg6f0/eGn/Sumgd84ddZF4CnxIDS6DFzkNz66++Y+efNm3dHnOf1QtORjhIZ6WAhDrmwRrrRZCyGDbs9UrC6dD/bQqeD/nmBEx8YreEEqfkBfq7/Zrq/p0+Q7bodBNm1xFPcmc5Uz9Tn97K+5R18t9jx9PfzkLrv28Nmexv7sV+OzZ+0/51EBKMYPF+39QRwBQDFPsrUL2zcsRxZ5Zg7Mp4R20ilHAFDMkyJJG7TWmZHzn3oDdwFYXejzleERAPQTkFwXHhTf7Ap9Ca6QAYsNIDBB0yEDQK2TVMZaSMqskSqOv0hpco7KckC3iP1FominC/OaAeBvAFC1Dw62wVfqELHuFO+lAe4a5rdO0XbhUGEW6Rs0AAfNHQS4B9E3wAd3kQ/eAUE4s8mJFHKGOxAcaEXlIi/aNlxsvneDLSMPNUDheKem91CND96yUgy8qB7l5+/VH/7wvyCMujmCskWjERo7HLHmbSiaPUpvHWBbDJ5yJw4BM+WduBi2YCGjjgj+6nPQKMuI+155E7XPrhdLxgCVDWPnQ6Vm4cL3dQGK+e7dG/X94aemd36Llk1hrbHYs6zwlbv19+DG3pf39skbmnQJInVHWvIlp21GoNKJKb9pQ+VFt6D6mvaeJdMO4bThPT/PgLgH3ICOTQ8iGd4IbitIRrcj0blWpw+9ZiOUxQtX6Tf084TvzIHBybHxF9dj629C2Pv4EETr/4xcMT72P7cUB9Y8AYtjIMgvkuGP0bn1x7ogT/w4qn71GhgUIONuj6vKy5tVyee3KGfBBYpHyWlb1OCvHOCtcoSWKKt7mMoafq9+5skjvIDfPRhE+3fCfwaAfIBE9Fla1m8LKObTimQahLoD9QZq7ek4XvsFWPoq9IIsMzBQJ3CLt4+2A8mdcenQB4BNp9OR3+nwym6wMHUC/toxP09IF0xf+wA4fEBWqQGfOB9ClRb9nR+7QjOXqv/htRMkA8D+OcQd6C22w1Pg6PkxlaABl4j8gDgo/cUK737TatLO5mcILMxg8PTPrxhm9mALAmKAe8sCqPram3oJffI9Cb29dtR37hYvXwFyRufDcNhRMCkbL5wKzRM0QO6YAIZc+DnkT6mGMzcXZqqLuJngKr4CWUMnoX1Hk6z878OBdS1CzkqnG+u/6zCLT/4mHKExcORVItpM35pVJ/Y+dWx9D23bo0LOcaEPBXeuVScbLVtj+sZdfiN8VTcgOHKOEM2dSMUbdDxPpvD6vJnf0b9aNvyKRShfOgXVl32bSTA6G0y0vPeAJlmLexiyRv0J9sAwRPbeh9Z15yCy/z6h0AfgLPwqKr9ym6TfhezJ98OwB/WvnBp0vOxfsxM7/3IS6p4cie6dP9F7ERtevwf24DA4C76MVGQfSL7RhjW6VotzMOw5i9G6qRHG0DOyMfSKH2DwZU1o/qgW6370PbxztU1aFIaj8DwB/DG2/ekWrP/R9Wh5/xXEGp9BMrIVBBn94ygM8gFPxXdI4mrkTRHF31Cm6lJ5WbPi90z8nmHkDyJq2r0p/T9ZuEfJ6qrU+XnSr1G36zhP/0sAqBNwNwB1h8N72m8XqA+kM1JqW50AdYbFopSm49PXPgDMvOosZfrER8CPfyjemZF2Q1pf4HPv0AfA4YXeX+DJt8JbYNUE4xAeQQWDXo3XLjRM0g5lIg4eBq+MoPvTX2oRZuKS9bbFGH7DY5h895M48b5lGPql8eD3vznDPXCGHMgb6QC5FctqgNwaO3JHelB28nDYA05YfaWwZy/JBEfOYASqyxFuioofoRvtu+Nw+lkcMLiZyZ5lR3D4IHTtOSholepJlXOs+Sm4B5wNV/EITcpUjZlMZ4Uki/Uueo+rwM97HfyVQxHe8yaiDQ+LMvGUjuMpMOZhPS4ViwtRPKMAAxaWMxoGvRfOnFx4B88X7/4BBMZ8X5hKA7p3P64z8MTusCUVZy5B9rglYldcCxrg3ChsMEPt8x9BpCdvhTfchOzxF4h4J2eCHgcW7t71Nx1n8w+Bq+QadG7+JrrrYzA+/i+vSf3HU/F98KcJtj78pnThVfiHXa0LE5WFD6x5jre6cHjPXbC4S8B/62w0ftSF7Im3on7lBHzy6x9j0Jlj0bDmbVg9o3QB1m6Krpc9egJaNqxHw0tTdTxbQU3GOPFPprIH5ip+4zz+Zwl95e8gWZzliocjtFRlT3xS8RumIVe0qPy5a5S79BtMUq7iy5QeAw15nKf//wFWLOiRSOkG99sCznOGdCZeWZBh4XM9TjjGMfQLwASHBxmCYUHG9ReOAGDNwXIDZbP94JWFDWtPUVr4PXeHzhkAKhLpwjkjvOjeF9a56KAvn+vXjnruBtKRvU7GwXvkDLVh0HwPdOH9YbgLhS8sqUL+1MHwVRQjUJWtQdiidBleNQBrd8vCfaQ5pt1dzmy7LmTLyhUyHqZDztSzMyBkezh4aACnX4k0Tor5X4YhX5gmhQvAws6CMbB6i+Gt/LpI7p+DIPYsG/JHu8D/20YMDaBvbBY4cooQbayTlf5OpKLdupCv6uew+U9AvP11kZd7UXbaV1A4b6EYH1XgrggNwG+9U8kU2j75CJHGFngrhqDlw026EA4eBGFrCMirPVisU4zXLlDmuBsWIjRmhI6of7cV2x55A/GOuK5ZR8qJLejc8pKYAlfrligRFgNOGQmDu73qXnxZmj9ECsX0/7p25VhR9rmzpFjfv/Ytu0GQdKwjdxCMgnEulC45E1kjH0DR/M+j8YM2kf8p/ZzO2FP73Rh48XLtXwmOe1QPbN3zK/D/AQAA//+gYjpwAAAABklEQVQDAE0Pu+qTrtCmAAAAAElFTkSuQmCC" + }, + { + "name": "fire_1.png", + "path": "", + "folder": "block", + "namespace": "minecraft", + "id": "1", + "group": "", + "width": 16, + "height": 512, + "uv_width": 16, + "uv_height": 16, + "particle": false, + "use_as_default": false, + "layers_enabled": false, + "sync_to_project": "", + "render_mode": "default", + "render_sides": "auto", + "pbr_channel": "color", + "frame_time": 1, + "frame_order_type": "loop", + "frame_order": "", + "frame_interpolate": false, + "visible": true, + "internal": true, + "saved": false, + "uuid": "a1e23e75-4999-af28-9876-8ac4a39742b9", + "source": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAIACAYAAACLuuzTAAAQAElEQVR4Aex9CZhcRbn2W+f0vvfs+z6Tfd9DIAkJWSAJYd9EVETlqnBVRBQVEQUBQYWrLIIoKigokrCHLSAYCAESskP2ZCaz79PT3dPd5//e6vRkgklU+P2fe//n1jN1zulTVd+pqlPvt1b3GPiY6X8AgRVzYB1vlMcdworZsJQ6svkTJ8NaKTlz97gETDtgdwOrlsF6/gxYL52nLIdHmqYkH/ozeH5uKaxnFmOwqy+cCeu977uskhlO5I2xw5tvwJMjOduAv9iAnUSQTpqAJU1dQQU+4a+fNqzCqV4EqnNRdPJUZI/OQ7jWA3e2DTaPASsJmLZ0Yx41gcKJTuRP9MBfaMLmVOhvjWOgJ4JUvB+OrGw4gi44Q3b4Sj2oWDoMgRKTbXU2OFEFsyfCW5IFu9+EEpL9rUlEWyKItjbBXTgKxctugjvfLz1woHvnATjDJl69REm/AaN8lgPO3OEou2AfQsNy4SlwIHukG1njquAIZyE04SG4Cj6LsnNfgN3r1kS8RV6YDgUmg+M3Xdno2fZlOLNy4Mp2gff69jfAX7sIbWtORd/Oa9Hw5BL07m9D1wdd6NjWDWfQxHPydoz2DwbQ3/AW2t78M3p27UXH1m4M9CbkiffIhEXhypuIhufuQtMbBxDvGpBemHIfiHUmsXCljNiTLV1JJVBxSQNCo0fDnWvHuO9H4cw5B8m+g9i/4g6UnXMXJt8+gPE/jGHs9VFM+3kCeRNDHAGM6vNPQO7c13DwmfFofOUtpAYs7P19qS4MTfwjys+7Cb0f/AqJ3jfRs/0r6N50Gbo3fx41l7fJUC3L2PbAa9jwXRda3tyGzl0xeAo9KL9ovyaw/0/V6HjnLmz4yfN45VPTcXDVA9j4k1+h/pmH0PHWcrxwpoJx0m8sNf6GmBp3fUzxuu6LHSqTys7ZpYqXbVbz/mSp+X+GGnZFl5r1q5Qa+fVelTV1hTrlL+Bbx8dKsmw+Vnv8+wmsnAPriXmwnlogiD1VrofwAvb9qD146hRYa75g6JxdbcCXq+DJUnCHlb4mUTZm1gR449klsJ49DdYLZ8HKH2tDqMaL/On5CA/3IFhugytswOFVgPwZdgwmTSC71kBOnQ2+fENXSvRbSCVS8o6UYMMLh0CZa99TYEfhdD/8eepIArkTQgJnNxx+A3xCtDOFaHscA10RuHJzkTdjCtx5TsGBDbH2GJwhA6tOT3Mw49VPKstbnI+qS36PYJVXWJeJQLkdgcoA7EEP/MMWw1M2F4Unny4EHDBdJtw5dthc6V4YylCweYPo2nCzwNkHV5YdhqkEeVF4iivQ88EqRBteR9u6Vehv6UdvfUxyXA8Vkoyegyn0Nx5A55YtgvcOdO+LIRFNIe+EGVIMTbx5zRq0rm9DrGMAhk3J/FiI91m63HB49Rm1X2yHvyIH7iwbRn/jIeTMeh6wUmh5420Uzl+GqXcmMPY7f8DIK67BrAdSyB3l0g2N4ll+ZE06A/v+UIGOLU3SxkL9yi8i2b8NefPWoHjx2Yi370Zk348RrX9Crregfe3pGHH1Zqk3yjL2v9KDDx64G63vNKBrT1zmwIGqzzTBdA9H/V+GoXvrK9h6/xtY+42rceCpR7H13sdx8MUX0PTcaXjv7s0wiqZ7MPHmOCbeEhcu45N3nu5avP0JFJ+xHQdf2w9vgYk5D6cw6lsRVJ8zCcULl6Bo2RYsesqCMfqbEZVJI77ao2o+36Y/OrOX6fO0/0qqKbcn9DUPBQveUuFJj/BSZ0PPxMc4/Dcm8OLZSotznjVSBa0U888ITxg64sEhrJwLi/npRbAooUPVNuSNcyMs54CIdHdIwe5RssxxRNIEqDyEyxS8OQpOn5Sn5PUIRkynCVe2Q9Bnwhkw4Mk1kDPCDvYEh5LBc3adHd4iO5x+BSgBkqzzWHcSif4EnGEPskblCgJtsPtMJGMWnEEFqjqQZFAz8ZV4UbJwOvylDs22vHkmPPl2aWCHt6IS3tIq5Eyqgt1rwhT9wSX8gKoPJBmGDbAH3ILIvQJnJ5whE4aI7lQsBVdOANGmBsQ7m0Xw1iPelUB/WxL97SnY3NJa/oyFT0BFW3rRu7tFiPQj0pLU8jE0Mh/KMGDYbGjfsA/tW3sR7UgKQiHlEMhLa/kztMomQy9ZciHc+W64ggaqz5+D8gv3QUnjzu2NyJlShxn3JDH80sWovXAq5v4xhawamzQHjLwRJoLDKtD8+l/QVx8BFNCx/m307f4+Ss/ZifxZE2AlBtD57vnCSKJSbqBp1RTUXHyGCGWnZTRvTWL/c4LxTZ3oPpAQxmqi9ksdcGTPwf5Hq9G7Zxd2/nkbNtz2CA48+1fs/OMbaPrbJrS/vRp7/xqDkT/KxNQ7EiDHyZ/gkffuAlO89UUULvo9mte1ClEDs+57H+N/EEPRSUXInlCB0rN+haUvyXph4+jB+9gGI77eC5vPifY3l2LfY7fj9ctnonNvUucd907G5pu8QrARu1e8j8bnv4QXz1IwlCR30WVyTP9VX9qssqc/qagDzPm9pRY/DbXoSajhV3ap0d+KqKk/TagTH0ip8vP3qvmPQRn4mOnfR4ASmsh8eqGgVEQ61z7FPDXboZ0+ag+IzlC5gZzhNgTLDPjzFVwBgKo+l/7fEeBqXLU8rUCQYRgifQgau9eAO9sENXlnQGmghYUwe5IhontAXuDLM+D0KRgmZJ1bGBBIp+IWHEE7glWyxLNMOHwGqAazNziUDJ59RXbkT8uBT9R98gSXcB+XQNYm8PUWBuEpCiM8LChwNmBzAqyzQlQfSNIEHAE7En1xOMM2YRaGVFL6Sc6gQ+yGfmEsMZHMfRiIpBDrthDvtWB3QidNINY5gEhjBNH2AamQgshU+MvcUKYUKyUaeie6RIuNiuKRSgLJgXQmBakhJwXhOOVwhWwyToWSuYUonH8mDIcpukAfwsOztESuWlaOikX5OOnuXyBYKo2kqcFX5i/1ofuDBkQ7ElCmElh3ItHbiJrPtyJnQjGU8IWmVZNF4HphD/jQ/OqPUL64HK98QlkG9d2mtzvRuaMfvY0pMfMUys66AvZgOfb8tli4VDv2v9CA7b99Bwdf2Y59z+5C24aDwuKaMft3ljJePl9ZJ9yXxMxfJpE7xinc1wFfzY1IRJoQHD4NrRt7YNoVRn1hPkZ97S7kjPaLIhJAwexZGOh9xzJm/fJN9O26ThSHJ1B76U9hDzjRsHIkGl96Ae/97HFhMin0NqdwcPVr+OCXX5ae9qJpbQc63luHF8+dCKPznasRb3sPO++/ULjMHQjU1YKyPzSyHPEeCzWnZ2PBSgsdH0TR2xBHrCslOsJY1L/WgUUCdSN39mrR/R9XI6/uFdtgiyo4Za1iKl62RS1YCVX7hTZ+1LbEzHtS6qQHLVW4eL0ir4AkQ/LH+vv3EHjyFFgU69RiXzpXWc8tTav7Q1GY6fZgD1i4co4wj7mwCBi7B7IqBc5ZCoSy0we4g8DzZ8LKNObZ4IFPoGh3SCXDJus8DoE0BBMWHGJP+4ttsswNQaMSuCvQ+MChpAn4CgzkjHTCm2uAmiuf5hDeYHNLD3IdIqldCFQ4YBcFg71jnUPtYfDCKcoDEegSuegUHYHcSCmIeDeRjKdEpKUE1km5hkDa0r1jO2aDh3hvSoA0gFhPCjQ2eM+dZ9PdRQro2R9FT30Cse4UkgnozDrMmgAvgpVeOIRlsZv5IuJyJ5WJMmGILjCAgPCGsV89GyWzAiiZ4cH4y+tAHgpJmoBHtJFIcxQDfSnRB0TF6U5AGQrVn75LszLTbUP3tjWigHjFKPciUt8shLx4cj4sTaDj/Th69g0g0pqCKdpJ3ozhIiND2P+Xr4iN0I/GtV3Y83S9gKgZjWvaNKAiLXEseUGe85QIDirSJ/0uhexhdoGzDf66RaKFxODKzULH+1HpKFB2Sj7Kl46T4chbybMje1weTQTLGP/FkWKJn4GerV9G2enzQQbb/OoDaF33Pnb8eSd6hMn0t1vo3NYmkN6IvsY4iMy+fR1Yf88eGH17hZU178T+lQ+ge/u7oq2UaXvBXx7W3Ld4mhNTrz9bvwW+iWinhbxJQTS+E8Gyl2UIjiw/enbuQ/eefmz7QyMOvLgda6+QSdvdjmHnFqNrdxzb73sM/R0WZv/WUlFh6w2vdyFvrAuWJKPiov1q2JVdasbdKXXqc1DT7kiqaXcmtT+h4uJ6jX+WLXqK2hOwWJjI3D9Yaux1UcVk6Bn6GIdjEuDboXVKTZai/VjPOCoBQtvphZaB7rASOAPUFUiUvGIoMSPzYeiTMuKLZUQlUeoS8U79wLTz7uGsCdDkD1ea8GQp8CkON7SAISpdYbmfY4OvyEzD2QFQe8mQMHhBOJORZDiP6QSUCdjFX0CYWxAEippPV2AiLtcJuXHoz+CZEI6LyB4Qv0FSKigFzYEMkZOWGB+RpgT6mpOIiZwQp5deQGzHrAnwwiM2gt2tQLM+q8aOcJ0XptgGceERnnwbqk8vRv44B/JH27D5R17tV2E7TcAl7g1WTIpKw0lKijvMdNlRvGAKApUuGYqJeEcv3Lku0eidYrUkUTDGxvbQBHrqkyKZk+iXdW7ILIeHBwXOLvEZvCesLIG2LVE0rOlG26ZeyRH01scFJ8KqhIQmMOlbSzDzpz9FuMKEW5Qpb1kJIGO3ee3o2jsgPBHIGe1CroDInWMKYk1RvFx4+2q7ZWz8gduKtuwWj92jKJpTIYU2dG7eiY6trTiwulMkswUCqE8EKx2RUVFz+hoToDo06ZYBZfAi1tqGxtfeQd+BFgRrczDiqh7NyuMRS7w7JoafV6C5Va94O8hYA6V2tG4VRQkQFii8v3dfp8A5ht2rutH05kG8daUN/cIjS0/0ItqRwoGXm3Qv5j1KOAOt2+LIFrdRx9vnCkcSI8JwGCg6MQ9zf/0QRn/1ehTPH6Yr7X6xD8UnhjHh219HzjAbKMGo9o7+/ETYPAY23fkoDCWJPoSqTzcqV96Fylv5bUXdgLrTkuehai9vV/66W9TUnyUULTzqRYWL3lETfhhXJ/5adCQZxjH/jgfjTCMjc/HhM9V8px+g65fg+bCan6l/TAIpWSdKSh0eJWtDCW8ASDSjIx9BgEyC6h55AguoJ9gEtjYRMjS03VkGvOLdt7sBm9xnnUw2eOH0QYADeYoCiZhOyPsFMvaxUoCVtIQLA2Q2bJPJBi8I4UQUIr4tXcGQu+RESuBMfaRf1kK/sPV4H7D0xTR3ZjtmqcqTPF1YlildpgIREI8FV5spcCaPcIntUDTdjewaA/RuvPFFkzwGTJqAU5QKOhZS0k2ikQV0NuRNyoa/yKbFfkog7haZ6BXeYIhJREWb9TSBvjYLEcmxHsCUQjoibB4bevZ0iTZiCSITaN0cQ9euOLr2DKC/PYlEjM0BTWD4OTkYfdlwsOs0sDz5XhmoAp/U0yCVhdH4JaoRFD2Jc2N3K+mZiRfPUZbx2qWGHk8yLhWsLwAAEABJREFUEkH+5CAcEjfoPdCL7r0RNK2P6p7FeyGgSqLv4IDWkaLCeGj+EFzGgEA23hVF++ZGxNqiCFT4MO6GKJxCaCACBIoUSmc6Rcm2hDekNGN1hRQ6dslKgwzBsEEoR+WJA6h/sx9tm7vx5pdtoqknkScMlK+3dWscMekFwRSVeeo6kAIN0s3CXI2J370ado8pLMuD8VdOQfmSUcga7pcnJND4XkLuO1F7TgWCJQa4Yj1ZQNXCIChL9r/WB2PX736quxysK4avdikKT92A7t29qDglhNNWWRh7Xb9w5G5ZYBbqlocRLLWh6e1uzVTpFjDGXR9TTCVnvq98ld/lpZp8W0LVfalTX/NQIz7G2aJc1H2xQ/MF2gyz7k8pmYL0a+TF0TLVOErqo5Vl7hmZi6OdDRNweAD63I/FXAYJEIVDmQYbmAJdLhwuLncYGKqlZx6oCbCrNhdAWK8Ue4GFfL02AROZCnvCe0fLmgAlbmpAsC5im+KcROxuQJkALOjFQ5yctkpWuNwa+qcJSB1ZCwpEIjkOAxI+CRVwCOQVHEZOnYmXL1A6/kAzCIeSJkCNJJUQMvJHInyyXTT3rDqXdkKSgBLm4sk1QFche8eJJQ1NYPEz4tHrBuIRgOPVlTwGKPbIB3qbUujckwBFW19TEuRMHOoggXe+YbeqFvrgk8gF1RxXlgBEKZajryWlse8Wbc2TYwjvVHqonux0ucGu2H02uWlou4ncKdo2IEr1ANo/SGDBCij2jE+NimQm5yKCOTeQZNAbkYgk0SP4H+hLwlfqRM0nloIenIF+aMskd5gB6lAR0dpjwlhtEt04+RFLd0FkI8SLmRBtPInmTQPCtmLYdt9KsZ1SCFUYws4hZSlwnk4TXZq5r9WSQB2sVy5WllG7PEs/jaGgmqVZyJsYFN3Ars3+jj1CpNxE8QkeUJeUHmuNtWiiHU6x8Agwo21TF6b8dEAskHyERo1D7X+0a2ZSOsuDJS9YmPyTZr16THFCvHONwwoUGejamxD7St65UDSoQMgZpeeswb4nX8PfLjNh9xgoWrCEt2HYsjDymj7QLKKcoPJZenKW5o2sYMx5yFJMprNUUec54b6UmnBj/IgYAsuZyTtoS9CnsPBJ3bHj8wM+gfyA2OD10bJeiUcr4L0nxS4kP3D6RbQvQnrQLBiSBwkQ6x9+EsHEpW0eXphDmqYvBwlQbNNTl76dZh5szHt6JUYyJUeeBwkQxmzAYi5vrn3TDpBXEH3BYoXnJEhBe4K9ZT3mQQIZdHHSyI0I4YDIQ3eWgkPsBr5CT44STYWf2TSdjfQJoMlH5YG9cIvosrkVqBvQyOgX5aJXLFhiISpyMQMkttUE6GxZe6VNO1scXuhlarBE5r1fGlCU2z1yX7wa7B0fQqVzkIBLNBCHcKBwlQ1OUTaIvP62FLr2C4iehqKVThlJ3VmjV6waTvogAd7sb0uIxW5JWMyG4tkFmnFwWJww8sAB0aGiXZBhQXOtxUJ4kEC/RCxopbfvSqK3ISHK9UGZfQtsyEocO+eHxjbzIjGDqXxSHTTe+A/TsosySduwaIoTQdFCyEx6myz0NFvwiU85d4SJpxenVyKFz18vUZYrCCxbDWXw6bN+lUTu+CDCowpQ8+lrtD5YOMkh1pmFMVeerdFpdwHUZsg3I/JWyK0gyaChJWcULfoSWt9uwPobb9BGZ8nCmbyN8KRHMOFHccx/zBIHtaEnOW+MA5xUVjDyJ7rR+c556N31HFrECqHYdkngNuekl1l+RJ502wBOuD8JBiqyJVbNQmPMt/uVPEX7Eakw8Oboa/vVP0r0KbAulwvPx8xc2szHqnBcAoQ3Vx1BxeujETkuATZmIy5lvn9efzgflQCflg4TAEQpoU4oM4zwTxFglx0CYb5zp7AzuwegNPKEAYYKuQozhIzMxdCzbuQGiBHep6pLVFLZJHfKAIllmgA50OoLlUUmSl8Jn059gItXayZi/lFv4FCUtFAmsELcp4ME3CK6KaqCJUq4D8BJi4kDulewQCizIpkIM59ONne64ID3DR44UXQFkoESVLmjXTBElC19KS082CuikfDmOX2XLZEWLNo6b7HQ3WBp9b51c1RLZQ6N1U59dmgTQeEhwiwz+HrsIu9dEkfNrjHhyTHk6SLyRRcg7lcth7X6AmURxmzAvOp0WLQheW3QRzr1pmuQO8aF8DAfyhbVwbQp5I00EW151Bp2XpnwSKXnhiKe64NQ5jxBklYwfDU3SmBymmgpfdj12DaxzBVK5tfCmXM2ys7fi+l3JTHz1i/Ak22ADqmQxJqWZSYxJApEwxOjxPmwU+tEJ/7GUp48O4pO3yr0D/8FRt6lw6YU8zPujoCvnaXGjLuTShkmGGPNHe2AHquw84NPjmH5Ebll9Ylg2OSDn+eLKaiw/WfBtFO2aMlGDf+JP4qr01+BGvu9qCpauknfG3rIm/uaqvxkgxp2RZeaeW9KDbuyi+vqiIf8yx+Mf7nFhxockwDXup6PQw0I8UOXR5yOSYCaiVvgywVDkW53AVzSBNxQCkclwIo2p1STtwEl4BKxRkWT4i0DLinVf4MEuMJ4Z6XAlAqFIauR4CIO+GY4JHnbrHJE1gS4RcItWOBSJfchXOMSsOTWuUxtwlcjMXPj0FkTUOym+AeUoXRYlKvzaE871OaIkyYQ7wP6OwAq0THxWnYdSGpmejQmekRr+aAJUJ3jrPsLFJyihbBHhPIywT3t5WdPJXOT2of+aBIeuoTBi1GXlIOhgXC1HQVT/bCJuffqJcqqXznSqpznFf+qAhtR2eB6yHAqttUEAnXTkDu5SGykJBrX9oAKdfFJeShauhkjv9GL2b9PYcKXh8Gbq6SHwItnH+6RwZlvW/cSok2dYKSfyjcdLVWfaeQDBnPuSbdg2m0P6Mjf+KuWaBcZCw3u+jPsJuqu6ERWtcl7egIPPjVWX2cOjqxlEsS4D7t/XYimV1fDLarg65caaThHW3t1vSk/S2DbTwNW564B4Uyb0bn+YtSvGIGGJ0eDTKfptbdx8LVm5M+eB6dodjaPSk/iyKv7VCYN/89uRYOK+xDDE36nSpZvU8VLNyv6GMd8p1+dIH6D7GkrVCYOYeBjpn8fAYJnKHT5+WidPWYPbAJnJaVEJxsSTDx/OEuVD98CuOIIJsI5w///vlb6ziABQpqMhACisKUeuETEerrasY+aANc3G/Gp7gBAzYTdP3azwyWaABUoat9EIDUQKtfs/uFqx77SBFj85Dxog4PMk1A5GvdhvQ9nTeC9611WuMpAsNRE9nC7KFQAQbblFq+19j/FklkGstcPt9WfNQF/ZRayR/mQiFro3JXQcq9omg/cmzPyimvFCWEJRoLW88uh9Si+Jd1aDgbV2N69HYh1xsHNjvP+ZCn6UEZ8vUeKAW/l9/Q5f/ZpGP/VuVj8dCNGXFAAtmOBsfRFKMNuYNTX1yEg3lzeZIfrHx+mLzOH0PjfI9HbgV33j0LPng54RDFjT/QQkrEkTM8ovYmB89G1L4G9T+1Ai4hz8oXGZyfgwJ9q0Lx2G5rWdSBQnQ2XEHCIhacJVF7wZf2g1ECzNrzm/G67Jtb2zgYUnvYeevfuR/a0y1E4Zyq4W0LCiGKc2cEQgsGW/rpbFZPpyFdiTCibZxg/qhFf69Fn+gs8ZVepvDmv6s88jL8hJtIEaYZCIh816x581MZs9+8jQIDxCf8oD/YgwzgyDQiwzPXxzoMEqEhkxBd5w/EaDS0bJMAnUuZRhaW0HlrpeNeDBFiJPTDtAInx8z+TNYHXP2voDZ3+QoVQmQEqVfTyvvkl02IgIgOcoxHUBPylDoQlykkQ0QHplDWeP86Ouk+fhWEXT8IJt5wDOi0Jng8T0QS4DynRlwI1FHrwPeI7nXBTHKGJf0T+grfgypuBglnDMPITxWhefZK14TqXlSGkCVAjK1s2DV7x0rBAKWDvQ2W81Nld8hUULtkoXg0HWte9g4GeBDJanSbABqJIg4rEuq/ZrJ6GFOpX12vJTK2dkN77uxK0baiX+EMErhyHFu+kbvBQNG8sT+g/cAdsbhM6hHpvEj07DqDgtHfRs2sf3EVlyJteAzorRn2zD77CtC5hvPtNh1WwcB36dt8Ad8kVYHgka9oTOPj0WHhLc6GUDf7qcoTGfhWGTd6xfhQw6ccDsCQZMlmKyVeVji3wmrnotI2q7LzdvFRFp72nnLnnKAle6M9DD8Yhgh/59P8rgX+WmXDijjoH/zIaSemjZt0DGtO01Bnhzey5olLFL0jROD8ecU3AX2hI7MyEIauT7g4ChR79qiVFqF6Wg10PFFj0ox2NkMGbdH0ybkB/IQMxDD6M+tJnULTsIVRf1oJA3TgUTMsCg3Pv/zxs/e1z6RAj22oChHP+5JBY5rwFKLnb8rfHYQ+cBKbsmc+ieNmtcGa50d8UEQwAK8U4Y5lUBQw7UH7R4zjx7t+A1CPizWhc2449AuH6vwzDgcfqBNpfR+f7XejcHYdD3KeuIJtLW57yJThrD5yIyP7HRWybGH5RKSbdcBf69nfAVzUVPTsbYLodyB6bi5MeTGHy7QPwFehnw3hVohRFp34fne9egPDkx7TvkK6Atjdug7ckhMCY++AryxVIj4EznMXn6SxuAxmKZRnjv/Vl9O1dgdCEh3VBx9vnYvsdIewRBaP+lUaZDydKz9sNzgPZGis1vzhD9IhG7P9jJYzAiDtUzsxnVSZlTX5U702mY5I5c3/oOX/+G8p0FKqy8/dwvknzo+f0THz09v9fayj/7LQMTiLhS/FOYzvTmFKa9zOfj3bWBF48W1kBEe204ukzJCFGN8tmuVEx26n36L9wJmX335PQBFIS7WQkI+Pu8MiKrTmzCsULF2HEV55CeHQR8ie48dZXbBZ3ANEUyJDSBAjnULVde2lYoEyFnr1NcBWeCHtwHgoXP4LCubPgLXTKErZgOhSr6awJmA6gZMFUTLhyPFZfpCzGVNo29qH+iR9oMV//+HK0rH0T3GrZezCp/QsZm1ITyB7hQmjctUI9Dk+Oicr5XtScPw6Rxj5xDbrRvasNAj2EanyY83AKU370K9AwgySDulDutNFof/s6hMZ+Agwd0lKJtbbAU+CFt2IyPIU+gXY23IVZ0gRw5l+idYmGJ0ZbRt1ZeUhEehCedB085d9E298W0c2HhtcOomV9pzRaoPli6bm7UXrOLk2AdWLNv0Xntj0wdqxoFpZmR/fm23UhcV/zubWIdVuo++Q8/TRdMOSQ6G2DM+9i1Hz2TzCoVBWJLpB74ouDkLd5hqu5D1sqZ9bzg/eGXohCoj86wov+lx/IxOqFJOeP/Pd/hwDXNcX7UOzT6GAYbc3lpkVtnnWO1s0jenD6amiYkVj5HB+KZpeh5sI5yB7jB7fV0EHH2ORQ9V8TMEzAl28clrg2IN49AE9JLTxlC8VztRT504rhL7LLqlVweA73xeCl6YTI/zCGnRkETbtKSEEAABAASURBVHyGRTp2xtH02us4+NytaH3jGXTvaEakNSGOy5TwA7ZKZ4MnukCDI8dpCezNM1A0yY6imSFEW+OwEkn07OlGMp6Cv8SBGbd+F6MuHQdGe9iWBJA1KoTIgR0I1o3C+G/fqr8oSA7oErXelZcFV5ZTb6/0lgTgLr4UBYvX45QVFt77nssyaB8occYGhs2Ef/il6Nrye2z9sR9tm7rQtbMfnuJh4snoQd2XO/U2ZMNZhrbXF6Br46WC2ASMhncSUKYpDsntAtFPoGDh2yhd9nkptFBx+mhkTX+SPT0iD/S0IDjmfhTPHQ5jwcMPCscpQMGid9C//zZdsXf3y6hcUgJR7/XnzCGy92bse7gc0eYmtL5+CvY9sxWGq+CTSioqJvoIeOb+w/IL9/PyiOytuEaVX7hPVV5yUOXOekFN/0VS6UnMPOGjnP+XAA6rOEOhzMlcORcWQ+fMz5/Bdcm7f58HJ1Gpw4UU70UTbSic5kPF4nzkjHCAUNZmwZIjiQ0ScIcOE6APgXFFb2kOfJV1yJtWjdxxPnGVmQJlBT4Ah5ImQAaRM9KBt79u11E8xhW5Bbl9YwPa3lmPrvf3o785ilhPCox88AGH2qfngNpJsCYLzpAdXvHgk4Vl19nF259Aom8Avfv7kei39Haq0ZfWoerUIPhQSNI9CFY6MNAbhb8qF8M/PR1jv36liHWb1twdAQccARucYRu8xW746+Zg2BWdmHP3N6C3E3GWbS4TvvIiGe8YxFoPYs8jd6NrTxS9BxMC5xxtkHOT3/CvdCMw6h5Q2e7b/RKYDDrilU0h2R8BrfZSEeP5J0wC92GUnFyMkrN2sN4ReaC3E/mnrEXOaA+M3Q8WWZ6CAIqX/xV9O7+DVGyfMNRWVCwqhCDviIb99T/X8YVoSxsO/LkWLRsiMBj+i3X0QRl+vP/Lm/HmlZVofG0nKj5ZP9g43vEsOtadBWV6kIjEUP3ZZunZB5h68+3ptzBcYgqGPaQm3jygZt6TUpN/PKCGJmfWYpU15THlLvyM4h7FTJmn9Cv/yw9kmg3Jx/yjts5MaB+r0jEJcLdLwVg7Sk9wIafOAGXmUBRmCBqZi6Hyn8yFq5M/XxKozBYoh5AtPCFQpEDRn2nD8yCBsITD//opZfEm9QR+Mah7Tx+6d7dpnXmgJwk6K5lZJ5M1AW5OClQ4RYiaoGFBgPkLDXHYp/R3nPsODoCef7e4w7mPcd1Vdv0gEtEE/EUGrKQFf5kHVUvyUXd+rUDYhMNvaN8at1dxy6W30I7QiAqM+OJ12PdIlQ4VGJxhbh/yFPngLckTPSCBlnV7EGlOItqRhKfAg1Ff+yGm/GQAY78XRdaUb6Bj/W+RjEZhcwEGPTa0WMgqi894DzWfb0XWmELQq1EwNQT+LoKn7BvIJNMzXKDfj9CYuWm3ybqrbJYn34Xcmaej673LEBEJbCWTKDs5WzfONOQ5sudG7Pn9ItFcutG65hl07U3CmPzjhOLX063UAPY88ig23PQttK5vQvXnWthG50TPG+hcfxESfftkrlKibHTo30MZ/dk6GHwDo6+NIDj2Nxh/YwzcwNlzIKH3KW74thM7f5kr+sATSPa1SNdbwQ2Qmqoc9jyxA9peyOCbZ26b5PeVuE9x/A/jquZzrcpfc6O2HbKm/JlVBvOsX6X+lx/IRBqSj/pHSfzapw2LGjuxMRStQxsck4DNpeArsSNQ6RYoO5FVbehttxkXGA4l49AZVCL41Mxn2o2R5gGRyjHExRVOtwAt/GWr0yZBpp4mQAbiLzbhyTJAU5hMwyWRbRKJdSXBXyRISiDP6VegC4A2wxEEuMXaEJPfV2xDiTgdyk/2wxVUsHuUtg9MuxJprbR4Dw0LouacUdj0Q48FSboHTp8Sbdwu0PXCEMW7Z18/+PSBPgueXDuqz52A8d/+HiYLpHOmnCxgaoXh0E3Too3uQEMifgUnX6D35QarvcIXINLXhTHX9YsCvk6s+O8ID9gBm79C3AQJUQdyQe5l0H/izrEhPKoS0cYNaH9zGQy7KQaHDwQZhqS+XT9GwzP3Itbej67tjdDf/Z8nAcqUsDMrkcCB59Zi+6+eQucH3ai65LeDTeMdz6BDvHzx9g/Ad8BNDaO/HcGmmzyWQV4/8UdxhCZ+FtUXfwqxHgs9B5J4+5tn4r3rXNhxdw66N/0Y/Q1bRHfoE17QKUNoRLzjabS+1w9jyYsWujZ+Gqlok6gv92LOQyn9Gw+FM/Pp9UDH1k4xRMahaOkm5M17A0yGvQCO8KmYLXUNgjs09tcqE3PkZ+bKTx1U4yWmOPWOpAoM/wlvHTWn3wXJfsT835gA3w4BRv/604soNY4+xmMOwe4B/BIKCpbZkFVjgoSenP/3hAYJUPddOfdwBe5+i3WLcO1Ngb+DoJ+v9PGIwyABurboxSMRZlro1FZJpL/dAp33vEf9mLIkQ0UTYBSPey58+SYKxtm08e0MKBGeCkpqKBPaAefJMRCudqJ8XgBrvmBaJGLw4PRD6wb8whNZGZkI9YFEzII7yxQ5mYURn5kIRr2zJ1aJeLNE/OumaTibZBguA7lT6jDiP++Fr9gBbqvKkhjkxBvXo/yCJ2QZv4q+Xd+FI5jHZ8KT5wKHqsm4wob+RYFkpE/gfCsYsCuY5MLEW+JgUN/mnwHqydGmdWh+4y3RWuLobeiHVg00OTlYyRQa1+zF7pXb0FcfRcmpp8ldyBuoB6OAbX9bKLbEPihDYez1UUy+bQB00OgeTP9FAqGRY1E4qxIx8eJ11yex9Z6/iDNW4HzvaLSv+wV6d20WYjHwu4/RxvsEwZ9BT0MShkT8rLY1i2HITObNuw9zft8IYTIiC3wS2UyiY1sPnDklKP/EAZScJQxF+uUq+Kz4D36FUx63YHBjQvaMZ2Dz5mPLraeg+YWF2HKLD9lTpmgmOu2/EsiZ9YI0O/wXPXifrIs92PaTAIzSc3YqpuCY+9T4H8RV4anr1ahv9Kmh/kWWD83uosuUzVWpRny1R+k5OEz7X7/69xIgwJ4+DpTZ32P24ImTYfnzFQLFBuisfubUw0hlw0w+JgG9E0AEqoaywMYQQGUaDT0PEqBUpnGRKWT3uTMo1muBsoJ7l4naoVBm3UECdjfgldA5RfdfP2VYLkGo6ZAqKp157Q4r0O+2TrR1ykUpSaORlF0hA9xKS8U7Gbc0Gq0ERMwbKJjgQvWSHEy45gLxLYZhE+S6BYCDBEw7QJWeTrnK5RMEqqaWSoFSA8MvPRmlS5cif/YnkehtkohfALRmnOH0pBik4hLu4yuS/spk9e3fB4dXeMMoO8Ze8z0dIgtPegS+utuQ6GlDx+YGwUhCmwJsqwmQZVFCt23qFKd8C/hliPyZ1TBsPkTr70T3lsvR9PwUxNpaoESTGfa5KzH5xge1XqUJjLxsNgLVOQjVSoMuC9yXtGfl+9h+1zXY+8fvom3t4+LR3CVKRwIU64lIIzre/rH+yqKGc7yrRVhVGDnT52Dydy/AvD/uFe+lHf3iAu14vw+OUAC1l7eJP7FR5mEtQuN/h4LF7+pvHxrbbg9o0W26fdj/5LPo3vY3gekIZI8vx4x7kjoXL9/O4eps801FZN/NiLc9jo3Xu4Uf/LUHG77jxM5H3kTbVtEJu3plpt0yWfsRa/2TbsRDrOlBnnTecf912Hbn+ai+5DswTnkcmg/QbzDvT1Dce1Tz+TbFvYiu3HNUJrkKLslcqnHfj6lx18eUt/La/+78gMB54ez0jjk9+KMc9Do4yn19i9KJvwWiTOBoop2VjkuA+5MJ6YE+ETBJVgeOqe4TkYz+r1oOi5oJPxu2dCNLTrxmyCBQrEDIUy7K7TSceUFAEe9UvDXzYivJ/JxTZ6JMHBHDLyhF9nAXnAGBfhZbIU2A3aJKE6pyio4cFpFuaBr8Hk/lqXniwa5E3oxRMBx2OLPdMB1KEyEJgwenD3DnmDBEY4/3xMCvY2XXmhh20VjkzDgXhYsfQ/6CdSIbB9C7twc0zGkKsK3BA2eZs921K4qW9yLaEZc7NgRbIBeJvoPofPdrOPBYrejHvVCGQtmiYRj+ydGgpaMJVCwIw1figiffhpjAubc5hYa/tWPfilfQ8NzTaHtnLXp2HkRqIImqiy6RoTjR39iE01cLvfZ1Z1umU8aW40P2uGKMvKQaE686Sas8fY0JdOyIwuZxgiHEYf/ZBZu3HAXiyK+6tEnYnkT/dz38OIpP/y/YXC60ra8Xc6YDjavXImtkCBO+83Vw+xArc6jMnoprhUN9Eb3vXyUGmB1G44YENv3oQux/YR/aPxgQAv3gD0321ffASvTBSkXYDrGWh/WZh32PPYAdD96JnPG5Yi+8AJUQCTTzl0lwHUSa4qBFwn2rOx68VwbpYRs4cy/QZx6GXfEcxv8ghpa3m9PrYPrPk4pp5r0pNe2/0te0FSb+aIC3/y47gifpe/yuo0GKHycflwDXOzHB87EeclwCXM9Kapj2YzVHeg6OVUxDm74z7o45Vh2hf7iISgUZB3PmLrXRzDXLubmHOXNvkABVGVcIILA0Ng7VoN5ADYU/WVA5z41wtQ2usMJTp3CAODwEwjlQYiJnlAPkDQQKnZDF010onBpA7sQckV4uQa1dVq0SxEIng0fOslv0A8p9K2HBKX6CcJlCxYIs5E4ZJqL9dHGVnQeavZGWuMhIC5wbSNIEyK7kWjRwAc+uhBRaCNcJ58kO8jb69r8tvrNHEO+OQVYQ8icFUTHPr8s0gcLxdvETmHAIq4qJsh1ps8DvNDW+vg9Na7ahY+Nu9OztEDinUHwyfY1uJKNpLmtsvc1vOcN2uHKdCNd6UbUogLozsuEQ70VvYwr8bSBDONVY8SWKuIOroBb5J18l8N6JhqfGWkbL+l7kz5oGm9uO3vp+oZxA965uhGpcGPGpcTjptynUfuFFZFLW1BXor39RDJNPYOejG2Gc9FtL7Xj4VTS91YlO/r6DRDkhbCvWNSDWSgCx5t+DIr3/wE9lCM2ItfwBDS+8jL0rXoUnzwY9B0kxrvgrrXwTcbETR1+zSj+w/vk34My7SF+7S/5TmG6ewPp8VF7wNUy6Na4nXRPgek/0rgV5woy7kzjw5/OgpBfuHBfe/aZDHBCXaSI8WMleeKtvQPNLM/XwNAH6Du3+aSqTqj7TpCbcGFcSU1HkCbQlMmWGza8v8+et0WdNgJQ/av6HBFbMTq/5Yz3gHxLgF4GO1Zj3/yEBVhqaV845skdHECD7ysA004iopKay+kJlce9uSEA21Os3SIC2AqVxuNIAvXkkwHv5o0zkjXEIzN1w5dgFzqZ20mWYziAB8gC7WwHyR+n84tmwiqc6kTM2jDwJF2aNr4EhEbG4OCWo+vArfZA0SECu0S+OBgIoJTwhWG4Df87IdDkQ7+xE9wd7JEiVhJIWWbV2FIqfAZLkI0CvhCukxMkArUBHOyG4SKBtcw/aNragc3sbeg/0CxYs5IxGUx29AAAQAElEQVQLwhl2aELSHgY3LnpyTXhybOAPMxdPsaNkhkNrIb1NKXTvS0hlhZpPfgJ0B3hLi5AzdRKqzlsE/i69wS5z15/NawrHSQpRhVhnEoFSG6oW5+DE+99C5XkXa2NbCpFzwo/Ez96JyIGtaHo3CmPRU1AHXm4URTuK7vokou0J1tN8z5kVQGTPXQiM/iX4g+799Xcisu8PaFm7HQ2v7AEnXc9BMgZM+cH3QWZKg6ti+WQoeRut7xyQxvdpgv7hd8Jd/GWExv8ORQvmYuodCW0OagKUAwM9u3Dib1IgX+jcsg0QAqbbwHoJEXRt/AwyKd6+EtkznsbBp8eBP4uoCbAHkX3rMnVgcwsP2J9EzsRaDP+Pn4mvsQP0FXS+e6EYXpt0vcJTN+CZRQqawDxxi2a+46gkVV/WouY9ainecxdfrrKmPq59BeGJDytvxbVSI/3H8LImgI+R/ocQoFinps79es+LNk/LPjPqI4ZAnL94jrIobDMV2Ci71kB2rQ2eXEMr4g5vphTpt8CP1APsIs5MO0AdgR4LeuyyRzh1uDAsTnmb09CClyog2zAf7oGCXlkRgTS/ihQoMrTksfvsSMYSiDT3yTkFJfXoFmHPBgnwaU7x8Bs24NRnofj9dyKxa28cXTsj4A8NRRoHtE8hVO0UDcUUtLI5YDy9EJY3V+mx+QsMvH6ZYXHDLxlHX4sF+svIRkvmV2H45y+GryyArNH5KD25ENwVYXA1hWtdsPsM0E9i2pU++wsNFE9zYdyVJ6F00WjkL3gUnrKLkDXxFP3ogd5+Qa+VnsTmDVF07U2gT+yEmPA81uA8uPM8sAZiyJ3zR3Rv/Bb6dt+PWJMoHFub0fJuF9hLA5ISIp1rz67Q3JYMs2BKSAqV6Ak9CE+5UbT3OmRNfwqhCQ8jf+E60ZuqMOrLnwB/wU4T4OTZPF7M/UMK3MAYlQCEUkJZ8uZbFqN97XL5kP7r3fFNsaO+g67NL2P6tdPSQ5BQI+JdnUhG05sV7D4HIq0pBCr9KF4wHbHmndj+k6AW6al4l+gMF6L4jJew9qY30w5JMgbT6UTv9u+DadiVnRh9+QnIm3UG9j+9BvtXbUXnzj5suGMN3r//l2h/a7kMqwbTrpsNQx1K9CuGxv/20Cel8ua+poJj7leTbhlQtAtoUyxYATXl9oTKnrpC18ub/Qrnkc/86FlP4kdvDvzTBCjWCTh+A2/oA48gQJw/LUt7aAVKaoYGwhUK6SWvjvAlHEHA4QG4zY6EyBNePl9Z4SoT2cMdCFY6hVsrAZQFrtLMQwYJsIuMKXDzP6fWl6c0A3EGbbpuvCcpjQGW0W1I+wKSBgnYPdCF9GTyi5HRTktjo7dhAIz+97clYUlEzF9kQktyF3TSBMjK3CLePdkKDI8yW1IcEa2dfIGByrzxflScVqmN9FCtBwUTXaBKpAkES03YvUqaQOsIkEt2M3ekiZrluSiYmSurciF8VZMRHlUl8yTDkifQGDPYqmN3En2iC3CbMTcs8R6dsJ48B2weF7Knnibm/jZxje1EvLNDbIdetL8fY7X0OqD5UjjVDbuMiwwzLIEJZSiJt8YRqJsCR3i83qeXL16M7CnnITwsjIpFRYcJEM6uHA/m/8XC1B9erlUZpQAS2/OnJ9Cz/WG5jooH41nJ2xAedwLiXX3Q4UKSYUUrkULfzmvhrbwC3AEV60mJkmVH1ug8RPbvETjnomX1FULVQnjKX5A/+2zwRwuNyL7brPl/eEbgaUe8832Y7uE60jniklHIGlOGlneacHBNE9q3R7D1dx9gz2PPg/EIai0f3JVtGe/dfDU233q66Ef9CE96lB3SuXDJJnH5FCHWlRL1zkLH7pT+DVUqWtkSj2Alb2khjOniO5h4U1zLf/WhlDt7tZr1q5SiWbREHBXjvhc9okbRkk1Kv0ZS+6j5/w0B8gE66CjaeT20t0f0gHoAoZypQF7Ar+YR0oESc3C5Z8p5PoIAkbj0RSIBoEJBcLlCBgwRd6kBS9AIcNYojHEoHUHg0D194lcUo+IWi7SlxEGdRLRTCKQgEQCl3QOZnmoC7DqtkueWwCJ1jpOrk2w8IpDmVsNQlR2F03zwFdpEKbchp87UD9IEaKk4BM7KBg0oYsMdAui5LJkuGspYN3ImlsFfVYRgbVjmwpRh6fYweOptsvRPoXKbMf2onAWKeY+YAc4spyzpaiT7+2VFRiTHEWkaAMPrbKsJcPKyhHmadrllAVQ02Iu4AMpXli/2coWOteWd+BUEh1XDX+ZC3njBvlTXBOQs+pAdJ9x2OUZfWgMlMQT2gmM/+NpuMfe3I7L3ZnFO7haoxxGsKwG1FhorgwTYKNa6Bb6a6XAGTXBHpMNvSPTTjd59Tdjz8PfR+uafhLiJ4uXbZE5qMOv+lDJ23JtjNa6aYtk8NqFqITTut5hwUwy1ZxUjWO3TSlbrhh60bevHricOouGlzRLtmIrCJRv11zaN/S+14cCq9cLzU8id/QpHo3O5xBc9BdngPMRkLrr2C/FKm7ab8k9Zq+sE68IwuLJatgygY3s/3r8jpAt46Nl2BUrO3oETH0zh5EctzLxpmTgdBsDQaSpezyo4+LdWGHMesvT/WCDuh13ZpTIpMOLOzKU+Z09bqc85J6xSprNEX+s50KQ+xmHwLfwjGrSVmT9c77gE6Hzg/nQ64/yFCg4vQCE8lIgx9MPQawKMwXyXyEybU8krTpcqM33OHI9JgMub4j7WY4Haa1zChkSoK5DmFX9HYKVEOPnUFXO4SNPF1NwjHdC/bu4TRTxnhB3cmk89mhIcknQPyAOcHmiIUj5ysujJeH45rLwRJrJEVmaN8MNf7kOwwgUucWoy0h6awOKnofijgqc9B8WNS0pBRDjgyTHgFqs+VBcEwWVJfD45kEKsMyWarMAWSBMAAF+uwsq56e67xeVJONOO5u5AV242Ss+8AVnjJoiCERTkmghVpGdT90AIyU0D4z5XjppT/frp7AU19/Yt3SKROxHZ94xI6CS4z99fzjoKZH2DBLjzge/KX10EVzBtfPAeod13oBsNq15Gx6aNMk8mipd+T3SEIBY/A2Vw29j2O0OWXRwQptujsc7/jFK5ICi8wI4+iTG0bY+ibXsM+1d3ovmtg2hb8zPUfKFV80yjfWcSHdt6oEwlcYatHI3O/L6Ct8gL7hYke+8+aImiaWLy7QMapayUNcwFg+6c9h1JdO6M4f07Q7yvs/6fbF9ow8xfPIWFT4jmcvV4TL8rgdbX5mOg+1Vdp21rlPEFC8PPL8C4qz+P3OlzdQEPgVH3aLsA6RcDRjh5n3sR7IGT9B6FvPE+GEpS1acbVXDU3Yp+Avk4+Ee7wJl12uDnoRfcozDiqh7yI9L96HnwNR6LBPFBsbfqdFhDv7aXqX9cAlRlXUGA7h72ValMs8Nn4/Dl318RF/xVEmqvhDbVfHr4MkueLY5LgAEKrjYuaY/gI1RmwJOl4M1RWtE+ggDHyhtDMyFNoyMoQfygiHd/iQOBEhucEqu3u9M1B3tADpS+lT6SJ7jlaR7xWgQqnDAdBjgP/P11vTq70/WM9AnIWCD8TAZDOJOFuenFzPUi/8SJCNbmwp3nFIPD0PCHpEECHBv3HPK7PeRKSskaFAule18ciUgcA12tUKYN/LdTvkKHvBlpLX+DBGhwUMAGKnwyRgMU7YZNaUOr72A/mtfuQfeuJg3n3BljwGFJexhU5dZdZbcc4oBwBN36PyPNeiAJbvb25BniHkyhc3cCHR/EcXBtBB1bu9G7ezcqz78MbGvQn9gvBpXpMpA/72skqvOY7/bDV+gEw6P9oqHNE9WAs1936XmovqwZ/uF3IKvahMHanftS6Nk/gH1/vkHG+hJvoeOtMzDqW32Y+M3T9T6D3b8psk78dUpcAaKt7LtZbx+gA9Po3nqFVb3Qi6ozqhEePRz24MmaQFiMilbBvrfsDP0583WEfDF7uIP6g3sugq/AhOEf/jOJl/TCEcxBzokP6cqZg8Z+eH7moz5v+0kAb/yHDQkJ0kwXU0HzAyUpf/4byuaulasj/zK6QOYu9yDNuCupxt/wL/weCsGTUW11N4YcjCHXR70kpLnuZQ0dtfwfEqBzSsM6ftT26dd49KL0XYYLaS/xzDvkTpnf1OTnf9gDrjaK8szZl2/A5VfIwP+4BDJGB3cSZ9fZwDMhTaGbgb/Bbnw4U8mgLqQEka6wKSLejuyxOfCVuuEMmXD4lP79eUgaJMCnMarJb05oOEsJ+UF/a1K8exZS8YRA2SboNOHJNUGHhbQ/PIkOMTicomT7Sx1wCcsiA2V3aYT0twygfWsn+hr6QM4UHhEGPRmDBBigcMrEuMS4GHXNm5h28w9QON6mQ+lxUbK6DyTRKYHMlo1x8W5GEeuIoOikMjAZPNC3bvcayJk2FTbvOLiKPom6z14Kb76s+RjEmoE44qGoL5TMK0fVxbej9NxdYORHE+BXkvoak2h+bQ16tl0JKxVHf8N6jPzqPRh5SRVOuGkxtv7YZ530a3HMy8z2N7yAjnVnCmELxrafBi1+l6uQ/x2zOl8Yxc9guqog4ELXez8XZ8NyZEs4YPjXemC6RyJvzg1wZI/B/iee1nzRKD3jWxhz7TPwFGcjd9Y3OaLBrLFfcZhLsWDPQ5dj063XI9aVxPw/QxmesquFicxD6Tm74MhZhr5d17GezvyvkoajSF/zUL9iBNq39KJjTxLtO9KhFEMNSaajQPmqvz94p/yCvYPXvChZvk3NvDel7QvyUhLVk8iL4+WVcw6pKUep9E8RoJA9Slt9658i8LF6QGCltWL9wL87HLcHxLwnDGRJCDHjqCTBzDWpHZeAMgGqve4sQ8Bj4K+fNiz+yAh5JBszDxIgZbo+V4mNQFuJhZz7mBidRGa41oVQlVNWnwFX2EBG4Rok4PRCo89faMLpx2CqWJCD8mUzNQr7WwdgOJQYHQ74RM2BJE2A/M5JOGfbwC9Ij7lsBGiZOwNAYNhIbRLXXDBLr74+Ub6T0RRyxrilOYYwFGFT2WOLEBx9Nfy1J6Ny2XB4Rb1Z+8NX0fLKbFnuJZj2gwsl3uJD8cLpKD/7Pw7bC/ljHRIuTaFjy0F0bvghlOlAMhZF9bnTxAAJIDTuWngrLtG54OSl4s3oRufGFYj3Ix3x7GtOIHuYA94iv+6ur+52FJxyl1gqzciZOh320ILBzH6bLh+a1uyBIRNgFJ9UgOGfmS8WmTSeeToGOlexjm4QGrMMgZGH4ZwaaITNWwx38QzRXJIgazf8NaORPfM5lJ59v4xzlNgC69H7/ld17t7+nCZEisnoLkT23I7O9/6ic/mpVbwNo2fnJtFGlqPx+SvxzvVXYdeD3wOHwFy0dLOu1LP1SyCXYuOWdXsRGnsGtjy4Q38xxqj8ZIPYCSsUsU9/wJjv/P1vKwdG/lwxlZ69Q0380YDidx34I50LHoeSadAP+ciH/wEEjqXaZMb8w6+g+gAAAa9JREFUD4dgmBi0DdiIUT6qPbxm/ocEZFWLb01pcU5GYvcoUPiyMfMggaPxPboD80bZQd87XYZBMTxMgbNPnBFE8FACmgdQP9hyi1ezQDauvWCc2Ahh5E/wIHukB137Uxp01BvClSbbp+G8UvwG5AeBcpdmHCRSMC2ESH0DPMVF4L9dqzj/WpTP9aLm7ErQHUgipKCHMOaSQsRED3Bme8XdmSbCHYOsEJ74VYmtXQzTXQJn2I2enU3wFAY0EZYbnNGBvijqzhIibX0Ij6lF7oRslumn84I/HOLMuxiFC7+K8NgaKJsN3fuiLIIx86ZzwS/8ecurkT15PPy1pyI0eqpuzCEk+nbrHuja4kjp2PAB6l+uB39SnveMtrdfFo/lHXAXTxc4F0kY5D1kTXsC4YlfE0/FbRLt3w32gLnhmVvRJn7FULWLbXU2Yu0RaXwFIgfWYNsv/4zG1S8j1vw7XejM+wRcBScj2vgSLJk1X0UZpt3+OGo+97DeLcVKRuVFN0pk4zvwls1F3sRsFMxJ+xDYmITi7W+h4blH4cq/BFlTr5cebUb72uv09eabPNb/AQAA///MzLGqAAAABklEQVQDAIljUGXrwS8lAAAAAElFTkSuQmCC" + } + ] +} \ No newline at end of file diff --git a/core/src/main/resources/internal/player_model.bbmodel b/core/src/main/resources/internal/player_model.bbmodel new file mode 100644 index 0000000..2888039 --- /dev/null +++ b/core/src/main/resources/internal/player_model.bbmodel @@ -0,0 +1,1262 @@ +{ + "meta": { + "format_version": "5.0", + "model_format": "free", + "box_uv": false + }, + "name": "player_model_v2", + "model_identifier": "", + "visible_box": [1, 1, 0], + "variable_placeholders": "", + "variable_placeholder_buttons": [], + "timeline_setups": [], + "unhandled_root_fields": {}, + "resolution": { + "width": 16, + "height": 16 + }, + "elements": [ + { + "name": "head", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 24, -4], + "to": [4, 32, 4], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "faces": { + "north": { + "uv": [8, 8, 16, 16], + "texture": 0 + }, + "east": { + "uv": [0, 8, 8, 16], + "texture": 0 + }, + "south": { + "uv": [24, 8, 32, 16], + "texture": 0 + }, + "west": { + "uv": [16, 8, 24, 16], + "texture": 0 + }, + "up": { + "uv": [16, 8, 8, 0], + "texture": 0 + }, + "down": { + "uv": [24, 0, 16, 8], + "texture": 0 + } + }, + "type": "cube", + "uuid": "773085fd-ece5-a5b9-5e19-73fd8aa66ffb" + }, + { + "name": "hat_head", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 24, -4], + "to": [4, 32, 4], + "autouv": 0, + "color": 0, + "inflate": 0.5, + "origin": [0, 0, 0], + "uv_offset": [32, 0], + "faces": { + "north": { + "uv": [40, 8, 48, 16], + "texture": 0 + }, + "east": { + "uv": [32, 8, 40, 16], + "texture": 0 + }, + "south": { + "uv": [56, 8, 64, 16], + "texture": 0 + }, + "west": { + "uv": [48, 8, 56, 16], + "texture": 0 + }, + "up": { + "uv": [48, 8, 40, 0], + "texture": 0 + }, + "down": { + "uv": [56, 0, 48, 8], + "texture": 0 + } + }, + "type": "cube", + "uuid": "57175ec5-3265-02a0-2add-cd194f195826" + }, + { + "name": "body", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 12, -2], + "to": [4, 16, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 16], + "faces": { + "north": { + "uv": [20, 28, 28, 32], + "texture": 0 + }, + "east": { + "uv": [16, 28, 20, 32], + "texture": 0 + }, + "south": { + "uv": [32, 28, 40, 32], + "texture": 0 + }, + "west": { + "uv": [28, 28, 32, 32], + "texture": 0 + }, + "up": { + "uv": [28, 29, 20, 28], + "texture": 0 + }, + "down": { + "uv": [36, 16, 28, 20], + "texture": 0 + } + }, + "type": "cube", + "uuid": "55511b53-fdf3-ec80-d1df-2a30a7ab059e" + }, + { + "name": "hat_body", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 12, -2], + "to": [4, 16, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [16, 32], + "faces": { + "north": { + "uv": [20, 44, 28, 48], + "texture": 0 + }, + "east": { + "uv": [16, 44, 20, 48], + "texture": 0 + }, + "south": { + "uv": [32, 44, 40, 48], + "texture": 0 + }, + "west": { + "uv": [28, 44, 32, 48], + "texture": 0 + }, + "up": { + "uv": [8, 4, 0, 0] + }, + "down": { + "uv": [36, 32, 28, 36], + "texture": 0 + } + }, + "type": "cube", + "uuid": "47af0790-f0dc-a2dc-0018-82b2ddea8ad7" + }, + { + "name": "right_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 20, -2], + "to": [8, 24, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [40, 16], + "faces": { + "north": { + "uv": [44, 20, 48, 24], + "texture": 0 + }, + "east": { + "uv": [40, 20, 44, 24], + "texture": 0 + }, + "south": { + "uv": [52, 20, 56, 24], + "texture": 0 + }, + "west": { + "uv": [48, 20, 52, 24], + "texture": 0 + }, + "up": { + "uv": [48, 20, 44, 16], + "texture": 0 + }, + "down": { + "uv": [48, 23, 44, 24], + "texture": 0 + } + }, + "type": "cube", + "uuid": "48c97cc9-2210-280a-019a-468b7de7c38f" + }, + { + "name": "hat_right_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 20, -2], + "to": [8, 24, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [40, 32], + "faces": { + "north": { + "uv": [44, 36, 48, 40], + "texture": 0 + }, + "east": { + "uv": [40, 36, 44, 40], + "texture": 0 + }, + "south": { + "uv": [52, 36, 56, 40], + "texture": 0 + }, + "west": { + "uv": [48, 36, 52, 40], + "texture": 0 + }, + "up": { + "uv": [48, 36, 44, 32], + "texture": 0 + }, + "down": { + "uv": [4, 0, 0, 4] + } + }, + "type": "cube", + "uuid": "5003d649-ffbd-da45-da99-db3ced59a92a" + }, + { + "name": "left_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-8, 20, -2], + "to": [-4, 24, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [32, 48], + "faces": { + "north": { + "uv": [36, 52, 40, 56], + "texture": 0 + }, + "east": { + "uv": [32, 52, 36, 56], + "texture": 0 + }, + "south": { + "uv": [44, 52, 48, 56], + "texture": 0 + }, + "west": { + "uv": [40, 52, 44, 56], + "texture": 0 + }, + "up": { + "uv": [40, 52, 36, 48], + "texture": 0 + }, + "down": { + "uv": [40, 55, 36, 56], + "texture": 0 + } + }, + "type": "cube", + "uuid": "1d2562ed-3d0d-1e7b-ad42-46494c3d3f6a" + }, + { + "name": "hat_left_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-8, 20, -2], + "to": [-4, 24, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [48, 48], + "faces": { + "north": { + "uv": [52, 52, 56, 56], + "texture": 0 + }, + "east": { + "uv": [48, 52, 52, 56], + "texture": 0 + }, + "south": { + "uv": [60, 52, 64, 56], + "texture": 0 + }, + "west": { + "uv": [56, 52, 60, 56], + "texture": 0 + }, + "up": { + "uv": [56, 52, 52, 48], + "texture": 0 + }, + "down": { + "uv": [60, 48, 56, 52] + } + }, + "type": "cube", + "uuid": "8ed52da2-9b81-09f5-5905-eba9174b8eed" + }, + { + "name": "right_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 8, -2], + "to": [3.9, 12, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [0, 16], + "faces": { + "north": { + "uv": [4, 20, 8, 24], + "texture": 0 + }, + "east": { + "uv": [0, 20, 4, 24], + "texture": 0 + }, + "south": { + "uv": [12, 20, 16, 24], + "texture": 0 + }, + "west": { + "uv": [8, 20, 12, 24], + "texture": 0 + }, + "up": { + "uv": [8, 20, 4, 16], + "texture": 0 + }, + "down": { + "uv": [8, 23, 4, 24], + "texture": 0 + } + }, + "type": "cube", + "uuid": "ff747326-cd74-c195-704e-ef28f7c5d8f2" + }, + { + "name": "hat_right_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 8, -2], + "to": [3.9, 12, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 32], + "faces": { + "north": { + "uv": [4, 36, 8, 40], + "texture": 0 + }, + "east": { + "uv": [0, 36, 4, 40], + "texture": 0 + }, + "south": { + "uv": [12, 36, 16, 40], + "texture": 0 + }, + "west": { + "uv": [8, 36, 12, 40], + "texture": 0 + }, + "up": { + "uv": [8, 36, 4, 32], + "texture": 0 + }, + "down": { + "uv": [12, 32, 8, 36] + } + }, + "type": "cube", + "uuid": "0cd5a793-5d97-dc7c-5604-561faf7822c3" + }, + { + "name": "left_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 8, -2], + "to": [0.1, 12, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 48], + "faces": { + "north": { + "uv": [20, 52, 24, 56], + "texture": 0 + }, + "east": { + "uv": [16, 52, 20, 56], + "texture": 0 + }, + "south": { + "uv": [28, 52, 32, 56], + "texture": 0 + }, + "west": { + "uv": [24, 52, 28, 56], + "texture": 0 + }, + "up": { + "uv": [24, 52, 20, 48], + "texture": 0 + }, + "down": { + "uv": [24, 55, 20, 56], + "texture": 0 + } + }, + "type": "cube", + "uuid": "572cbd8d-3a02-5d54-cc8e-aad0616dbec4" + }, + { + "name": "hat_left_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 8, -2], + "to": [0.1, 12, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 48], + "faces": { + "north": { + "uv": [4, 52, 8, 56], + "texture": 0 + }, + "east": { + "uv": [0, 52, 4, 56], + "texture": 0 + }, + "south": { + "uv": [12, 52, 16, 56], + "texture": 0 + }, + "west": { + "uv": [8, 52, 12, 56], + "texture": 0 + }, + "up": { + "uv": [8, 52, 4, 48], + "texture": 0 + }, + "down": { + "uv": [12, 48, 8, 52] + } + }, + "type": "cube", + "uuid": "69fe31ce-0ba6-2c2d-6021-7a25b20b9770" + }, + { + "name": "hat_chest", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 16, -2], + "to": [4, 24, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [16, 32], + "faces": { + "north": { + "uv": [20, 36, 28, 44], + "texture": 0 + }, + "east": { + "uv": [16, 36, 20, 44], + "texture": 0 + }, + "south": { + "uv": [32, 36, 40, 44], + "texture": 0 + }, + "west": { + "uv": [28, 36, 32, 44], + "texture": 0 + }, + "up": { + "uv": [28, 36, 20, 32], + "texture": 0 + }, + "down": { + "uv": [8, 0, 0, 4] + } + }, + "type": "cube", + "uuid": "b767ac81-4abb-495c-c293-de417ee14797" + }, + { + "name": "chest", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 16, -2], + "to": [4, 24, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 16], + "faces": { + "north": { + "uv": [20, 20, 28, 28], + "texture": 0 + }, + "east": { + "uv": [16, 20, 20, 28], + "texture": 0 + }, + "south": { + "uv": [32, 20, 40, 28], + "texture": 0 + }, + "west": { + "uv": [28, 20, 32, 28], + "texture": 0 + }, + "up": { + "uv": [28, 20, 20, 16], + "texture": 0 + }, + "down": { + "uv": [28, 27, 20, 28], + "texture": 0 + } + }, + "type": "cube", + "uuid": "104ecd06-18b8-404b-0f37-8d51b98891fa" + }, + { + "name": "right_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 12, -2], + "to": [8, 20, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [40, 16], + "faces": { + "north": { + "uv": [44, 24, 48, 32], + "texture": 0 + }, + "east": { + "uv": [40, 24, 44, 32], + "texture": 0 + }, + "south": { + "uv": [52, 24, 56, 32], + "texture": 0 + }, + "west": { + "uv": [48, 24, 52, 32], + "texture": 0 + }, + "up": { + "uv": [48, 25, 44, 24], + "texture": 0 + }, + "down": { + "uv": [52, 16, 48, 20], + "texture": 0 + } + }, + "type": "cube", + "uuid": "38ed858d-8c7c-e8d1-0020-d597fac38034" + }, + { + "name": "hat_right_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 12, -2], + "to": [8, 20, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [40, 32], + "faces": { + "north": { + "uv": [44, 40, 48, 48], + "texture": 0 + }, + "east": { + "uv": [40, 40, 44, 48], + "texture": 0 + }, + "south": { + "uv": [52, 40, 56, 48], + "texture": 0 + }, + "west": { + "uv": [48, 40, 52, 48], + "texture": 0 + }, + "up": { + "uv": [4, 4, 0, 0] + }, + "down": { + "uv": [52, 32, 48, 36], + "texture": 0 + } + }, + "type": "cube", + "uuid": "6ad770bd-3bac-08fd-d5b7-138e26e069c8" + }, + { + "name": "left_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-8, 12, -2], + "to": [-4, 20, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [32, 48], + "faces": { + "north": { + "uv": [36, 56, 40, 64], + "texture": 0 + }, + "east": { + "uv": [32, 56, 36, 64], + "texture": 0 + }, + "south": { + "uv": [44, 56, 48, 64], + "texture": 0 + }, + "west": { + "uv": [40, 56, 44, 64], + "texture": 0 + }, + "up": { + "uv": [40, 57, 36, 56], + "texture": 0 + }, + "down": { + "uv": [44, 48, 40, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "07d13b5d-5740-9daf-9c96-e24527450262" + }, + { + "name": "hat_left_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-8, 12, -2], + "to": [-4, 20, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [48, 48], + "faces": { + "north": { + "uv": [52, 56, 56, 64], + "texture": 0 + }, + "east": { + "uv": [48, 56, 52, 64], + "texture": 0 + }, + "south": { + "uv": [60, 56, 64, 64], + "texture": 0 + }, + "west": { + "uv": [56, 56, 60, 64], + "texture": 0 + }, + "up": { + "uv": [56, 52, 52, 48] + }, + "down": { + "uv": [60, 48, 56, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "f29d51fc-42be-bd31-8d5b-5d3856518722" + }, + { + "name": "left_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 0, -2], + "to": [0.1, 8, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 48], + "faces": { + "north": { + "uv": [20, 56, 24, 64], + "texture": 0 + }, + "east": { + "uv": [16, 56, 20, 64], + "texture": 0 + }, + "south": { + "uv": [28, 56, 32, 64], + "texture": 0 + }, + "west": { + "uv": [24, 56, 28, 64], + "texture": 0 + }, + "up": { + "uv": [24, 57, 20, 56], + "texture": 0 + }, + "down": { + "uv": [28, 48, 24, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "6e9969e8-9486-ce88-685d-f9d885b2d393" + }, + { + "name": "hat_left_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 0, -2], + "to": [0.1, 8, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 48], + "faces": { + "north": { + "uv": [4, 56, 8, 64], + "texture": 0 + }, + "east": { + "uv": [0, 56, 4, 64], + "texture": 0 + }, + "south": { + "uv": [12, 56, 16, 64], + "texture": 0 + }, + "west": { + "uv": [8, 56, 12, 64], + "texture": 0 + }, + "up": { + "uv": [8, 52, 4, 48] + }, + "down": { + "uv": [12, 48, 8, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "cb210e40-f438-8286-da38-58c7c98a1d8f" + }, + { + "name": "right_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 0, -2], + "to": [3.9, 8, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [0, 16], + "faces": { + "north": { + "uv": [4, 24, 8, 32], + "texture": 0 + }, + "east": { + "uv": [0, 24, 4, 32], + "texture": 0 + }, + "south": { + "uv": [12, 24, 16, 32], + "texture": 0 + }, + "west": { + "uv": [8, 24, 12, 32], + "texture": 0 + }, + "up": { + "uv": [8, 25, 4, 24], + "texture": 0 + }, + "down": { + "uv": [12, 16, 8, 20], + "texture": 0 + } + }, + "type": "cube", + "uuid": "4790240d-8caa-c1a7-29c0-fb662f6ed69c" + }, + { + "name": "hat_right_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 0, -2], + "to": [3.9, 8, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 32], + "faces": { + "north": { + "uv": [4, 40, 8, 48], + "texture": 0 + }, + "east": { + "uv": [0, 40, 4, 48], + "texture": 0 + }, + "south": { + "uv": [12, 40, 16, 48], + "texture": 0 + }, + "west": { + "uv": [8, 40, 12, 48], + "texture": 0 + }, + "up": { + "uv": [8, 36, 4, 32] + }, + "down": { + "uv": [12, 32, 8, 36], + "texture": 0 + } + }, + "type": "cube", + "uuid": "bf00419f-2747-6d7d-6750-74cc60fae501" + } + ], + "groups": [ + { + "uuid": "5400c1a6-94b7-0533-294c-37501ba32de5", + "export": true, + "locked": false, + "origin": [0, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "waist", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "278df701-6051-1ac3-a7ab-29a01a41c308", + "export": true, + "locked": false, + "origin": [0, 24, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "limb[type=head]_head", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "23943758-ce52-7338-6c0c-353096f8338a", + "export": true, + "locked": false, + "origin": [0, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "limb[type=body]_body", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "f0181c5c-a850-6a70-ebe8-7706c029231d", + "export": true, + "locked": false, + "origin": [5, 22, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "limb[type=right_arm]_right_arm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "30ebd0e3-f52f-8023-f330-6653c3ebad9d", + "export": true, + "locked": false, + "origin": [-5, 22, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "limb[type=left_arm]_left_arm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "6a354ac6-dbab-f460-deda-6f279c2311e6", + "export": true, + "locked": false, + "origin": [1.9, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "limb[type=right_leg]_right_leg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "7e18703d-ce68-fb92-4e63-d0414f7f43ee", + "export": true, + "locked": false, + "origin": [-1.9, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "limb[type=left_leg]_left_leg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "05c86cb0-39d8-f6ae-8349-ab0e5cbc25ef", + "export": true, + "locked": false, + "origin": [0, 16, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "limb[type=chest]_chest", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "a71e3bf3-9dfc-6adb-f652-e1ad0b84539e", + "export": true, + "locked": false, + "origin": [6, 20, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "limb[type=right_forearm]_right_forearm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "0da46e14-aaab-9e07-5252-a78c28cb0a23", + "export": true, + "locked": false, + "origin": [-6, 20, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "limb[type=left_forearm]_left_forearm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "9d962bea-0e4b-fdf9-35dd-3d5266462cec", + "export": true, + "locked": false, + "origin": [0, 0, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "root", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "01f1fb2f-972d-1d69-8d72-6e908af47da3", + "export": true, + "locked": false, + "origin": [-1.9, 8, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "limb[type=left_foreleg]_left_foreleg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "d77c33f0-fa52-d727-f6f0-7fa68d177d51", + "export": true, + "locked": false, + "origin": [1.9, 8, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "limb[type=right_foreleg]_right_foreleg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + } + ], + "outliner": [ + { + "uuid": "9d962bea-0e4b-fdf9-35dd-3d5266462cec", + "isOpen": true, + "children": [ + { + "uuid": "5400c1a6-94b7-0533-294c-37501ba32de5", + "isOpen": true, + "children": [ + { + "uuid": "23943758-ce52-7338-6c0c-353096f8338a", + "isOpen": true, + "children": [ + { + "uuid": "05c86cb0-39d8-f6ae-8349-ab0e5cbc25ef", + "isOpen": true, + "children": [ + { + "uuid": "278df701-6051-1ac3-a7ab-29a01a41c308", + "isOpen": true, + "children": ["773085fd-ece5-a5b9-5e19-73fd8aa66ffb", "57175ec5-3265-02a0-2add-cd194f195826"] + }, + { + "uuid": "30ebd0e3-f52f-8023-f330-6653c3ebad9d", + "isOpen": true, + "children": [ + "1d2562ed-3d0d-1e7b-ad42-46494c3d3f6a", + "8ed52da2-9b81-09f5-5905-eba9174b8eed", + { + "uuid": "0da46e14-aaab-9e07-5252-a78c28cb0a23", + "isOpen": true, + "children": ["f29d51fc-42be-bd31-8d5b-5d3856518722", "07d13b5d-5740-9daf-9c96-e24527450262"] + } + ] + }, + { + "uuid": "f0181c5c-a850-6a70-ebe8-7706c029231d", + "isOpen": true, + "children": [ + "48c97cc9-2210-280a-019a-468b7de7c38f", + "5003d649-ffbd-da45-da99-db3ced59a92a", + { + "uuid": "a71e3bf3-9dfc-6adb-f652-e1ad0b84539e", + "isOpen": true, + "children": ["38ed858d-8c7c-e8d1-0020-d597fac38034", "6ad770bd-3bac-08fd-d5b7-138e26e069c8"] + } + ] + }, + "104ecd06-18b8-404b-0f37-8d51b98891fa", + "b767ac81-4abb-495c-c293-de417ee14797" + ] + }, + "55511b53-fdf3-ec80-d1df-2a30a7ab059e", + "47af0790-f0dc-a2dc-0018-82b2ddea8ad7" + ] + }, + { + "uuid": "7e18703d-ce68-fb92-4e63-d0414f7f43ee", + "isOpen": true, + "children": [ + "572cbd8d-3a02-5d54-cc8e-aad0616dbec4", + "69fe31ce-0ba6-2c2d-6021-7a25b20b9770", + { + "uuid": "01f1fb2f-972d-1d69-8d72-6e908af47da3", + "isOpen": true, + "children": ["6e9969e8-9486-ce88-685d-f9d885b2d393", "cb210e40-f438-8286-da38-58c7c98a1d8f"] + } + ] + }, + { + "uuid": "6a354ac6-dbab-f460-deda-6f279c2311e6", + "isOpen": true, + "children": [ + "ff747326-cd74-c195-704e-ef28f7c5d8f2", + "0cd5a793-5d97-dc7c-5604-561faf7822c3", + { + "uuid": "d77c33f0-fa52-d727-f6f0-7fa68d177d51", + "isOpen": true, + "children": ["4790240d-8caa-c1a7-29c0-fb662f6ed69c", "bf00419f-2747-6d7d-6750-74cc60fae501"] + } + ] + } + ] + } + ] + } + ], + "textures": [ + { + "name": "placeholder", + "path": "", + "folder": "", + "namespace": "", + "id": "0", + "group": "", + "width": 64, + "height": 64, + "uv_width": 64, + "uv_height": 64, + "particle": false, + "use_as_default": false, + "layers_enabled": false, + "sync_to_project": "", + "render_mode": "default", + "render_sides": "auto", + "pbr_channel": "color", + "frame_time": 1, + "frame_order_type": "loop", + "frame_order": "", + "frame_interpolate": false, + "visible": true, + "internal": true, + "saved": false, + "uuid": "141da3cc-5b94-4b80-7421-e066a92662f1", + "source": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAEBElEQVR4AeyaPWsVQRSG56ZRSApRMIGIH6jY+APSaykWaiMpxF8gfjQGCwtJpf4FsQhWWllGsMwPsBEVPzCYiFolGBuvvEseOExm59zNkOKOe+HlnHPfOe/unJ27O7NzJ4Lzefnm8zCHy9fvDHNw5F06d2xxuWOL8w7gFkACc6eOhBTC9md2eiaksE0Xmwtnjw1SQPj5k4eDFOBzdqQC5ATGnesLMO5XsPT8+xFQWsFxzx9pBKy8/xpSoPOr62shBfhSq8ddCujqcZcCfM5OnFt7NMzh2dqhkMPT0wdDDlsfbg1zyB1bXO7Y4nLHFpc7trhmBMxNHw4pULnjM5MhBfjJE0dDCvD7Zs+EFOBfzdwepAC/dH5qkAL81MLCIAX4/ScfD1IQ3xRAzv+KkQpwaTYEgSLJF4jH2Y5UgHHuoHfuIxXgxWoIAmLyBeJxtiMVYJw76J17U4CV9e8hBZI/rW2GFOA3P34JKcD/WX0bUoDX4y4F+PnljWEK8BuLi8MU4PW4A9aKn4gfPzd/XAkWW0v3g0X8OIofP68vzgeL5d83gsX8g4lgceDut2ARn098vKszP4PFtXe/gkV8PqnHn/2uGQGqhAVrf75jrU/sWfJjSx56sYX3LLq0Q4e4i00WoIvAuLdNFoB5P51jnk/sWfJjSx56sYX3LLq0Q4e4i92xFtD82kLzaQt7E5Ef37xsbsq3WvKX7v0NFtK08PSlYWFz5XvFaEYA6wAaM+8nZp5PzLyeuC0fHSzt2/TQxdK+TR++TQ8+Z5sC5BrUzvUFqP0Ke/3rR4BXodr5fgTUfoW9/vUjwKtQ7XwzAngXQGdZ+xOz1idmbU/clo8OlvZteuhiad+mD9+mJ97DjvcBdq0t36615du1tPx4/a6cHKRhYd8NyJemhadvteTbXPluAVIN2IuHY++d2LPkx5Y89GIL71l0aYcOcRfb/AS6JNTWNlkA9uHoLPtuxJ4lP7bkoRdbeM+iSzt0iLvY/n2AqsWNRr7Ai0j5Ai8a5Qu6uQjyhbZ8dLBqK7TpSdNCbYU2fXFCm544D8mfgJdUE98XoKaruZu+9CNgN1WrKacfATVdzd30pR8Bu6laTTnNCGD7iY6xF0/M3juxtpwE4rZ8dLC0b9OTpgXt2/ThrZ6+Q0O+hz1/H2D/WyCfaSvWTn3l2/8SyLf/HZDPtBqLDlY5FiyUsHFBmhEQf1m63i7dvy/N73L+yQLEBak5ThagdL1dun9fmt/l/Pf8fYDdu5fPDQrLDQ4b/6dAORbkYcnDds1vRkDpert0/740v+T8mwLU/Bv3+tYXwKtQ7Xw/Amq/wl7/+hHgVah2vh8BtV9hr3/NCGAaSeNR1++0L92/L8nXOZSc/z8AAAD//8OtMsgAAAAGSURBVAMADyxhOxK7d34AAAAASUVORK5CYII=" + } + ] +} \ No newline at end of file diff --git a/core/src/main/resources/internal/steve_mapped.bbmodel b/core/src/main/resources/internal/steve_mapped.bbmodel new file mode 100644 index 0000000..0e0c52c --- /dev/null +++ b/core/src/main/resources/internal/steve_mapped.bbmodel @@ -0,0 +1,1300 @@ +{ + "meta": { + "format_version": "5.0", + "model_format": "free", + "box_uv": false + }, + "name": "steve_mapped", + "model_identifier": "", + "visible_box": [1, 1, 0], + "variable_placeholders": "", + "variable_placeholder_buttons": [], + "timeline_setups": [], + "unhandled_root_fields": {}, + "resolution": { + "width": 16, + "height": 16 + }, + "elements": [ + { + "name": "head", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 24, -4], + "to": [4, 32, 4], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "faces": { + "north": { + "uv": [8, 8, 16, 16], + "texture": 0 + }, + "east": { + "uv": [0, 8, 8, 16], + "texture": 0 + }, + "south": { + "uv": [24, 8, 32, 16], + "texture": 0 + }, + "west": { + "uv": [16, 8, 24, 16], + "texture": 0 + }, + "up": { + "uv": [16, 8, 8, 0], + "texture": 0 + }, + "down": { + "uv": [24, 0, 16, 8], + "texture": 0 + } + }, + "type": "cube", + "uuid": "773085fd-ece5-a5b9-5e19-73fd8aa66ffb" + }, + { + "name": "hat_head", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 24, -4], + "to": [4, 32, 4], + "autouv": 0, + "color": 0, + "inflate": 0.5, + "origin": [0, 0, 0], + "uv_offset": [32, 0], + "faces": { + "north": { + "uv": [40, 8, 48, 16], + "texture": 0 + }, + "east": { + "uv": [32, 8, 40, 16], + "texture": 0 + }, + "south": { + "uv": [56, 8, 64, 16], + "texture": 0 + }, + "west": { + "uv": [48, 8, 56, 16], + "texture": 0 + }, + "up": { + "uv": [48, 8, 40, 0], + "texture": 0 + }, + "down": { + "uv": [56, 0, 48, 8], + "texture": 0 + } + }, + "type": "cube", + "uuid": "57175ec5-3265-02a0-2add-cd194f195826" + }, + { + "name": "body", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 12, -2], + "to": [4, 16, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 16], + "faces": { + "north": { + "uv": [20, 28, 28, 32], + "texture": 0 + }, + "east": { + "uv": [16, 28, 20, 32], + "texture": 0 + }, + "south": { + "uv": [32, 28, 40, 32], + "texture": 0 + }, + "west": { + "uv": [28, 28, 32, 32], + "texture": 0 + }, + "up": { + "uv": [28, 29, 20, 28], + "texture": 0 + }, + "down": { + "uv": [36, 16, 28, 20], + "texture": 0 + } + }, + "type": "cube", + "uuid": "55511b53-fdf3-ec80-d1df-2a30a7ab059e" + }, + { + "name": "hat_body", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 12, -2], + "to": [4, 16, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [16, 32], + "faces": { + "north": { + "uv": [20, 44, 28, 48], + "texture": 0 + }, + "east": { + "uv": [16, 44, 20, 48], + "texture": 0 + }, + "south": { + "uv": [32, 44, 40, 48], + "texture": 0 + }, + "west": { + "uv": [28, 44, 32, 48], + "texture": 0 + }, + "up": { + "uv": [8, 4, 0, 0], + "texture": 1 + }, + "down": { + "uv": [36, 32, 28, 36], + "texture": 0 + } + }, + "type": "cube", + "uuid": "47af0790-f0dc-a2dc-0018-82b2ddea8ad7" + }, + { + "name": "right_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 20, -2], + "to": [8, 24, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [40, 16], + "faces": { + "north": { + "uv": [44, 20, 48, 24], + "texture": 0 + }, + "east": { + "uv": [40, 20, 44, 24], + "texture": 0 + }, + "south": { + "uv": [52, 20, 56, 24], + "texture": 0 + }, + "west": { + "uv": [48, 20, 52, 24], + "texture": 0 + }, + "up": { + "uv": [48, 20, 44, 16], + "texture": 0 + }, + "down": { + "uv": [48, 23, 44, 24], + "texture": 0 + } + }, + "type": "cube", + "uuid": "48c97cc9-2210-280a-019a-468b7de7c38f" + }, + { + "name": "hat_right_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 20, -2], + "to": [8, 24, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [40, 32], + "faces": { + "north": { + "uv": [44, 36, 48, 40], + "texture": 0 + }, + "east": { + "uv": [40, 36, 44, 40], + "texture": 0 + }, + "south": { + "uv": [52, 36, 56, 40], + "texture": 0 + }, + "west": { + "uv": [48, 36, 52, 40], + "texture": 0 + }, + "up": { + "uv": [48, 36, 44, 32], + "texture": 0 + }, + "down": { + "uv": [4, 0, 0, 4], + "texture": 1 + } + }, + "type": "cube", + "uuid": "5003d649-ffbd-da45-da99-db3ced59a92a" + }, + { + "name": "left_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-8, 20, -2], + "to": [-4, 24, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [32, 48], + "faces": { + "north": { + "uv": [36, 52, 40, 56], + "texture": 0 + }, + "east": { + "uv": [32, 52, 36, 56], + "texture": 0 + }, + "south": { + "uv": [44, 52, 48, 56], + "texture": 0 + }, + "west": { + "uv": [40, 52, 44, 56], + "texture": 0 + }, + "up": { + "uv": [40, 52, 36, 48], + "texture": 0 + }, + "down": { + "uv": [40, 55, 36, 56], + "texture": 0 + } + }, + "type": "cube", + "uuid": "1d2562ed-3d0d-1e7b-ad42-46494c3d3f6a" + }, + { + "name": "hat_left_arm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-8, 20, -2], + "to": [-4, 24, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [48, 48], + "faces": { + "north": { + "uv": [52, 52, 56, 56], + "texture": 0 + }, + "east": { + "uv": [48, 52, 52, 56], + "texture": 0 + }, + "south": { + "uv": [60, 52, 64, 56], + "texture": 0 + }, + "west": { + "uv": [56, 52, 60, 56], + "texture": 0 + }, + "up": { + "uv": [56, 52, 52, 48], + "texture": 0 + }, + "down": { + "uv": [60, 48, 56, 52], + "texture": 1 + } + }, + "type": "cube", + "uuid": "8ed52da2-9b81-09f5-5905-eba9174b8eed" + }, + { + "name": "right_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 8, -2], + "to": [3.9, 12, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [0, 16], + "faces": { + "north": { + "uv": [4, 20, 8, 24], + "texture": 0 + }, + "east": { + "uv": [0, 20, 4, 24], + "texture": 0 + }, + "south": { + "uv": [12, 20, 16, 24], + "texture": 0 + }, + "west": { + "uv": [8, 20, 12, 24], + "texture": 0 + }, + "up": { + "uv": [8, 20, 4, 16], + "texture": 0 + }, + "down": { + "uv": [8, 23, 4, 24], + "texture": 0 + } + }, + "type": "cube", + "uuid": "ff747326-cd74-c195-704e-ef28f7c5d8f2" + }, + { + "name": "hat_right_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 8, -2], + "to": [3.9, 12, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 32], + "faces": { + "north": { + "uv": [4, 36, 8, 40], + "texture": 0 + }, + "east": { + "uv": [0, 36, 4, 40], + "texture": 0 + }, + "south": { + "uv": [12, 36, 16, 40], + "texture": 0 + }, + "west": { + "uv": [8, 36, 12, 40], + "texture": 0 + }, + "up": { + "uv": [8, 36, 4, 32], + "texture": 0 + }, + "down": { + "uv": [12, 32, 8, 36], + "texture": 1 + } + }, + "type": "cube", + "uuid": "0cd5a793-5d97-dc7c-5604-561faf7822c3" + }, + { + "name": "left_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 8, -2], + "to": [0.1, 12, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 48], + "faces": { + "north": { + "uv": [20, 52, 24, 56], + "texture": 0 + }, + "east": { + "uv": [16, 52, 20, 56], + "texture": 0 + }, + "south": { + "uv": [28, 52, 32, 56], + "texture": 0 + }, + "west": { + "uv": [24, 52, 28, 56], + "texture": 0 + }, + "up": { + "uv": [24, 52, 20, 48], + "texture": 0 + }, + "down": { + "uv": [24, 55, 20, 56], + "texture": 0 + } + }, + "type": "cube", + "uuid": "572cbd8d-3a02-5d54-cc8e-aad0616dbec4" + }, + { + "name": "hat_left_leg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 8, -2], + "to": [0.1, 12, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 48], + "faces": { + "north": { + "uv": [4, 52, 8, 56], + "texture": 0 + }, + "east": { + "uv": [0, 52, 4, 56], + "texture": 0 + }, + "south": { + "uv": [12, 52, 16, 56], + "texture": 0 + }, + "west": { + "uv": [8, 52, 12, 56], + "texture": 0 + }, + "up": { + "uv": [8, 52, 4, 48], + "texture": 0 + }, + "down": { + "uv": [12, 48, 8, 52], + "texture": 1 + } + }, + "type": "cube", + "uuid": "69fe31ce-0ba6-2c2d-6021-7a25b20b9770" + }, + { + "name": "hat_chest", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 16, -2], + "to": [4, 24, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [16, 32], + "faces": { + "north": { + "uv": [20, 36, 28, 44], + "texture": 0 + }, + "east": { + "uv": [16, 36, 20, 44], + "texture": 0 + }, + "south": { + "uv": [32, 36, 40, 44], + "texture": 0 + }, + "west": { + "uv": [28, 36, 32, 44], + "texture": 0 + }, + "up": { + "uv": [28, 36, 20, 32], + "texture": 0 + }, + "down": { + "uv": [8, 0, 0, 4], + "texture": 1 + } + }, + "type": "cube", + "uuid": "b767ac81-4abb-495c-c293-de417ee14797" + }, + { + "name": "chest", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-4, 16, -2], + "to": [4, 24, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 16], + "faces": { + "north": { + "uv": [20, 20, 28, 28], + "texture": 0 + }, + "east": { + "uv": [16, 20, 20, 28], + "texture": 0 + }, + "south": { + "uv": [32, 20, 40, 28], + "texture": 0 + }, + "west": { + "uv": [28, 20, 32, 28], + "texture": 0 + }, + "up": { + "uv": [28, 20, 20, 16], + "texture": 0 + }, + "down": { + "uv": [28, 27, 20, 28], + "texture": 0 + } + }, + "type": "cube", + "uuid": "104ecd06-18b8-404b-0f37-8d51b98891fa" + }, + { + "name": "right_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 12, -2], + "to": [8, 20, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [40, 16], + "faces": { + "north": { + "uv": [44, 24, 48, 32], + "texture": 0 + }, + "east": { + "uv": [40, 24, 44, 32], + "texture": 0 + }, + "south": { + "uv": [52, 24, 56, 32], + "texture": 0 + }, + "west": { + "uv": [48, 24, 52, 32], + "texture": 0 + }, + "up": { + "uv": [48, 25, 44, 24], + "texture": 0 + }, + "down": { + "uv": [52, 16, 48, 20], + "texture": 0 + } + }, + "type": "cube", + "uuid": "38ed858d-8c7c-e8d1-0020-d597fac38034" + }, + { + "name": "hat_right_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [4, 12, -2], + "to": [8, 20, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [40, 32], + "faces": { + "north": { + "uv": [44, 40, 48, 48], + "texture": 0 + }, + "east": { + "uv": [40, 40, 44, 48], + "texture": 0 + }, + "south": { + "uv": [52, 40, 56, 48], + "texture": 0 + }, + "west": { + "uv": [48, 40, 52, 48], + "texture": 0 + }, + "up": { + "uv": [4, 4, 0, 0], + "texture": 1 + }, + "down": { + "uv": [52, 32, 48, 36], + "texture": 0 + } + }, + "type": "cube", + "uuid": "6ad770bd-3bac-08fd-d5b7-138e26e069c8" + }, + { + "name": "left_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-8, 12, -2], + "to": [-4, 20, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [32, 48], + "faces": { + "north": { + "uv": [36, 56, 40, 64], + "texture": 0 + }, + "east": { + "uv": [32, 56, 36, 64], + "texture": 0 + }, + "south": { + "uv": [44, 56, 48, 64], + "texture": 0 + }, + "west": { + "uv": [40, 56, 44, 64], + "texture": 0 + }, + "up": { + "uv": [40, 57, 36, 56], + "texture": 0 + }, + "down": { + "uv": [44, 48, 40, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "07d13b5d-5740-9daf-9c96-e24527450262" + }, + { + "name": "hat_left_forearm", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-8, 12, -2], + "to": [-4, 20, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [48, 48], + "faces": { + "north": { + "uv": [52, 56, 56, 64], + "texture": 0 + }, + "east": { + "uv": [48, 56, 52, 64], + "texture": 0 + }, + "south": { + "uv": [60, 56, 64, 64], + "texture": 0 + }, + "west": { + "uv": [56, 56, 60, 64], + "texture": 0 + }, + "up": { + "uv": [56, 52, 52, 48], + "texture": 1 + }, + "down": { + "uv": [60, 48, 56, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "f29d51fc-42be-bd31-8d5b-5d3856518722" + }, + { + "name": "left_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 0, -2], + "to": [0.1, 8, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [16, 48], + "faces": { + "north": { + "uv": [20, 56, 24, 64], + "texture": 0 + }, + "east": { + "uv": [16, 56, 20, 64], + "texture": 0 + }, + "south": { + "uv": [28, 56, 32, 64], + "texture": 0 + }, + "west": { + "uv": [24, 56, 28, 64], + "texture": 0 + }, + "up": { + "uv": [24, 57, 20, 56], + "texture": 0 + }, + "down": { + "uv": [28, 48, 24, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "6e9969e8-9486-ce88-685d-f9d885b2d393" + }, + { + "name": "hat_left_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-3.9, 0, -2], + "to": [0.1, 8, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 48], + "faces": { + "north": { + "uv": [4, 56, 8, 64], + "texture": 0 + }, + "east": { + "uv": [0, 56, 4, 64], + "texture": 0 + }, + "south": { + "uv": [12, 56, 16, 64], + "texture": 0 + }, + "west": { + "uv": [8, 56, 12, 64], + "texture": 0 + }, + "up": { + "uv": [8, 52, 4, 48], + "texture": 1 + }, + "down": { + "uv": [12, 48, 8, 52], + "texture": 0 + } + }, + "type": "cube", + "uuid": "cb210e40-f438-8286-da38-58c7c98a1d8f" + }, + { + "name": "right_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 0, -2], + "to": [3.9, 8, 2], + "autouv": 0, + "color": 0, + "origin": [0, 0, 0], + "uv_offset": [0, 16], + "faces": { + "north": { + "uv": [4, 24, 8, 32], + "texture": 0 + }, + "east": { + "uv": [0, 24, 4, 32], + "texture": 0 + }, + "south": { + "uv": [12, 24, 16, 32], + "texture": 0 + }, + "west": { + "uv": [8, 24, 12, 32], + "texture": 0 + }, + "up": { + "uv": [8, 25, 4, 24], + "texture": 0 + }, + "down": { + "uv": [12, 16, 8, 20], + "texture": 0 + } + }, + "type": "cube", + "uuid": "4790240d-8caa-c1a7-29c0-fb662f6ed69c" + }, + { + "name": "hat_right_foreleg", + "box_uv": false, + "render_order": "default", + "locked": false, + "allow_mirror_modeling": true, + "from": [-0.1, 0, -2], + "to": [3.9, 8, 2], + "autouv": 0, + "color": 0, + "inflate": 0.25, + "origin": [0, 0, 0], + "uv_offset": [0, 32], + "faces": { + "north": { + "uv": [4, 40, 8, 48], + "texture": 0 + }, + "east": { + "uv": [0, 40, 4, 48], + "texture": 0 + }, + "south": { + "uv": [12, 40, 16, 48], + "texture": 0 + }, + "west": { + "uv": [8, 40, 12, 48], + "texture": 0 + }, + "up": { + "uv": [8, 36, 4, 32], + "texture": 1 + }, + "down": { + "uv": [12, 32, 8, 36], + "texture": 0 + } + }, + "type": "cube", + "uuid": "bf00419f-2747-6d7d-6750-74cc60fae501" + } + ], + "groups": [ + { + "uuid": "5400c1a6-94b7-0533-294c-37501ba32de5", + "export": true, + "locked": false, + "origin": [0, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "waist", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "278df701-6051-1ac3-a7ab-29a01a41c308", + "export": true, + "locked": false, + "origin": [0, 24, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "head", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": false + }, + { + "uuid": "23943758-ce52-7338-6c0c-353096f8338a", + "export": true, + "locked": false, + "origin": [0, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "body", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "f0181c5c-a850-6a70-ebe8-7706c029231d", + "export": true, + "locked": false, + "origin": [5, 22, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "right_arm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": false + }, + { + "uuid": "30ebd0e3-f52f-8023-f330-6653c3ebad9d", + "export": true, + "locked": false, + "origin": [-5, 22, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "left_arm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": false + }, + { + "uuid": "6a354ac6-dbab-f460-deda-6f279c2311e6", + "export": true, + "locked": false, + "origin": [1.9, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "right_leg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "7e18703d-ce68-fb92-4e63-d0414f7f43ee", + "export": true, + "locked": false, + "origin": [-1.9, 12, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "left_leg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "05c86cb0-39d8-f6ae-8349-ab0e5cbc25ef", + "export": true, + "locked": false, + "origin": [0, 16, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "chest", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": false + }, + { + "uuid": "a71e3bf3-9dfc-6adb-f652-e1ad0b84539e", + "export": true, + "locked": false, + "origin": [6, 20, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "right_forearm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "0da46e14-aaab-9e07-5252-a78c28cb0a23", + "export": true, + "locked": false, + "origin": [-6, 20, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "left_forearm", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "9d962bea-0e4b-fdf9-35dd-3d5266462cec", + "export": true, + "locked": false, + "origin": [0, 0, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "root", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "01f1fb2f-972d-1d69-8d72-6e908af47da3", + "export": true, + "locked": false, + "origin": [-1.9, 8, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "left_foreleg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + }, + { + "uuid": "d77c33f0-fa52-d727-f6f0-7fa68d177d51", + "export": true, + "locked": false, + "origin": [1.9, 8, 0], + "rotation": [0, 0, 0], + "color": 0, + "name": "right_foreleg", + "children": [], + "reset": false, + "shade": true, + "mirror_uv": false, + "selected": false, + "visibility": true, + "autouv": 0, + "isOpen": true + } + ], + "outliner": [ + { + "uuid": "9d962bea-0e4b-fdf9-35dd-3d5266462cec", + "isOpen": true, + "children": [ + { + "uuid": "5400c1a6-94b7-0533-294c-37501ba32de5", + "isOpen": true, + "children": [ + { + "uuid": "23943758-ce52-7338-6c0c-353096f8338a", + "isOpen": true, + "children": [ + { + "uuid": "05c86cb0-39d8-f6ae-8349-ab0e5cbc25ef", + "isOpen": false, + "children": [ + { + "uuid": "278df701-6051-1ac3-a7ab-29a01a41c308", + "isOpen": false, + "children": ["773085fd-ece5-a5b9-5e19-73fd8aa66ffb", "57175ec5-3265-02a0-2add-cd194f195826"] + }, + { + "uuid": "30ebd0e3-f52f-8023-f330-6653c3ebad9d", + "isOpen": false, + "children": [ + "1d2562ed-3d0d-1e7b-ad42-46494c3d3f6a", + "8ed52da2-9b81-09f5-5905-eba9174b8eed", + { + "uuid": "0da46e14-aaab-9e07-5252-a78c28cb0a23", + "isOpen": true, + "children": ["f29d51fc-42be-bd31-8d5b-5d3856518722", "07d13b5d-5740-9daf-9c96-e24527450262"] + } + ] + }, + { + "uuid": "f0181c5c-a850-6a70-ebe8-7706c029231d", + "isOpen": false, + "children": [ + "48c97cc9-2210-280a-019a-468b7de7c38f", + "5003d649-ffbd-da45-da99-db3ced59a92a", + { + "uuid": "a71e3bf3-9dfc-6adb-f652-e1ad0b84539e", + "isOpen": true, + "children": ["38ed858d-8c7c-e8d1-0020-d597fac38034", "6ad770bd-3bac-08fd-d5b7-138e26e069c8"] + } + ] + }, + "104ecd06-18b8-404b-0f37-8d51b98891fa", + "b767ac81-4abb-495c-c293-de417ee14797" + ] + }, + "55511b53-fdf3-ec80-d1df-2a30a7ab059e", + "47af0790-f0dc-a2dc-0018-82b2ddea8ad7" + ] + }, + { + "uuid": "7e18703d-ce68-fb92-4e63-d0414f7f43ee", + "isOpen": true, + "children": [ + "572cbd8d-3a02-5d54-cc8e-aad0616dbec4", + "69fe31ce-0ba6-2c2d-6021-7a25b20b9770", + { + "uuid": "01f1fb2f-972d-1d69-8d72-6e908af47da3", + "isOpen": true, + "children": ["6e9969e8-9486-ce88-685d-f9d885b2d393", "cb210e40-f438-8286-da38-58c7c98a1d8f"] + } + ] + }, + { + "uuid": "6a354ac6-dbab-f460-deda-6f279c2311e6", + "isOpen": true, + "children": [ + "ff747326-cd74-c195-704e-ef28f7c5d8f2", + "0cd5a793-5d97-dc7c-5604-561faf7822c3", + { + "uuid": "d77c33f0-fa52-d727-f6f0-7fa68d177d51", + "isOpen": true, + "children": ["4790240d-8caa-c1a7-29c0-fb662f6ed69c", "bf00419f-2747-6d7d-6750-74cc60fae501"] + } + ] + } + ] + } + ] + } + ], + "textures": [ + { + "name": "", + "path": "", + "folder": "", + "namespace": "", + "id": "0", + "group": "", + "width": 64, + "height": 64, + "uv_width": 64, + "uv_height": 64, + "particle": false, + "use_as_default": false, + "layers_enabled": false, + "sync_to_project": "", + "render_mode": "default", + "render_sides": "auto", + "pbr_channel": "color", + "frame_time": 1, + "frame_order_type": "loop", + "frame_order": "", + "frame_interpolate": false, + "visible": true, + "internal": true, + "saved": false, + "uuid": "141da3cc-5b94-4b80-7421-e066a92662f1", + "source": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAEBElEQVR4AeyaPWsVQRSG56ZRSApRMIGIH6jY+APSaykWaiMpxF8gfjQGCwtJpf4FsQhWWllGsMwPsBEVPzCYiFolGBuvvEseOExm59zNkOKOe+HlnHPfOe/unJ27O7NzJ4Lzefnm8zCHy9fvDHNw5F06d2xxuWOL8w7gFkACc6eOhBTC9md2eiaksE0Xmwtnjw1SQPj5k4eDFOBzdqQC5ATGnesLMO5XsPT8+xFQWsFxzx9pBKy8/xpSoPOr62shBfhSq8ddCujqcZcCfM5OnFt7NMzh2dqhkMPT0wdDDlsfbg1zyB1bXO7Y4nLHFpc7trhmBMxNHw4pULnjM5MhBfjJE0dDCvD7Zs+EFOBfzdwepAC/dH5qkAL81MLCIAX4/ScfD1IQ3xRAzv+KkQpwaTYEgSLJF4jH2Y5UgHHuoHfuIxXgxWoIAmLyBeJxtiMVYJw76J17U4CV9e8hBZI/rW2GFOA3P34JKcD/WX0bUoDX4y4F+PnljWEK8BuLi8MU4PW4A9aKn4gfPzd/XAkWW0v3g0X8OIofP68vzgeL5d83gsX8g4lgceDut2ARn098vKszP4PFtXe/gkV8PqnHn/2uGQGqhAVrf75jrU/sWfJjSx56sYX3LLq0Q4e4i00WoIvAuLdNFoB5P51jnk/sWfJjSx56sYX3LLq0Q4e4i92xFtD82kLzaQt7E5Ef37xsbsq3WvKX7v0NFtK08PSlYWFz5XvFaEYA6wAaM+8nZp5PzLyeuC0fHSzt2/TQxdK+TR++TQ8+Z5sC5BrUzvUFqP0Ke/3rR4BXodr5fgTUfoW9/vUjwKtQ7XwzAngXQGdZ+xOz1idmbU/clo8OlvZteuhiad+mD9+mJ97DjvcBdq0t36615du1tPx4/a6cHKRhYd8NyJemhadvteTbXPluAVIN2IuHY++d2LPkx5Y89GIL71l0aYcOcRfb/AS6JNTWNlkA9uHoLPtuxJ4lP7bkoRdbeM+iSzt0iLvY/n2AqsWNRr7Ai0j5Ai8a5Qu6uQjyhbZ8dLBqK7TpSdNCbYU2fXFCm544D8mfgJdUE98XoKaruZu+9CNgN1WrKacfATVdzd30pR8Bu6laTTnNCGD7iY6xF0/M3juxtpwE4rZ8dLC0b9OTpgXt2/ThrZ6+Q0O+hz1/H2D/WyCfaSvWTn3l2/8SyLf/HZDPtBqLDlY5FiyUsHFBmhEQf1m63i7dvy/N73L+yQLEBak5ThagdL1dun9fmt/l/Pf8fYDdu5fPDQrLDQ4b/6dAORbkYcnDds1vRkDpert0/740v+T8mwLU/Bv3+tYXwKtQ7Xw/Amq/wl7/+hHgVah2vh8BtV9hr3/NCGAaSeNR1++0L92/L8nXOZSc/z8AAAD//8OtMsgAAAAGSURBVAMADyxhOxK7d34AAAAASUVORK5CYII=" + }, + { + "name": "color_fetch", + "path": "", + "folder": "block", + "namespace": "", + "id": "1", + "group": "", + "width": 16, + "height": 16, + "uv_width": 16, + "uv_height": 16, + "particle": false, + "use_as_default": false, + "layers_enabled": false, + "sync_to_project": "", + "render_mode": "default", + "render_sides": "auto", + "pbr_channel": "color", + "frame_time": 1, + "frame_order_type": "loop", + "frame_order": "", + "frame_interpolate": false, + "visible": true, + "internal": true, + "saved": false, + "uuid": "7c2f025b-2b7e-fa39-5c27-e509cca95248", + "source": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAJUlEQVR4AeyTsQ0AAAyCSP8/uvEGN4MHOBA4ynkAMpBBMhrw4AEAAP//uBwiawAAAAZJREFUAwBJIAAhJFoqZwAAAABJRU5ErkJggg==" + } + ] +} \ No newline at end of file diff --git a/core/src/main/resources/pack/assets/minecraft/shaders/core/entity.fsh b/core/src/main/resources/pack/assets/minecraft/shaders/core/entity.fsh new file mode 100644 index 0000000..33cdf63 --- /dev/null +++ b/core/src/main/resources/pack/assets/minecraft/shaders/core/entity.fsh @@ -0,0 +1,147 @@ +#version 330 +#extension GL_ARB_separate_shader_objects : require + +#ifdef GLINT +#include +#endif +#include +#include +#include + +uniform sampler2D Sampler0; + +#if defined(ALPHA_CUTOUT) && !defined(EMISSIVE) && !defined(NO_OVERLAY) && !defined(APPLY_TEXTURE_MATRIX) +#define MAYBE_PLAYERDISP 1 +#endif + +#ifdef DISSOLVE +uniform sampler2D DissolveMaskSampler; +#endif + +#ifdef GLINT +uniform sampler2D GlintSampler; +#endif + +layout(location = 0) in float sphericalVertexDistance; +layout(location = 1) in float cylindricalVertexDistance; +#ifdef PER_FACE_LIGHTING +layout(location = 2) in vec4 vertexPerFaceColorBack; +layout(location = 3) in vec4 vertexPerFaceColorFront; +#else +layout(location = 2) in vec4 vertexColor; +#endif + +#ifndef EMISSIVE +layout(location = 4) in vec4 lightMapColor; +#endif + +#ifndef NO_OVERLAY +layout(location = 5) in vec4 overlayColor; +#endif + +layout(location = 6) in vec2 texCoord0; +#ifdef GLINT +layout(location = 7) in vec2 texCoordGlint; +#endif + +#ifndef OIT_ALPHA_ONLY +layout(location = 0) out vec4 fragColor; +#endif + +#ifdef MAYBE_PLAYERDISP +layout(location = 8) in vec2 texCoord1; +layout(location = 9) in float part; + +#define FADERANGE 12.0 +#define FADEBIAS 8.0 +#define MINALPHA 0.25 + +const mat4 bayer4 = mat4( 0.0 / 16.0, 8.0 / 16.0, 2.0 / 16.0, 10.0 / 16.0, +12.0 / 16.0, 4.0 / 16.0, 14.0 / 16.0, 6.0 / 16.0, +3.0 / 16.0, 11.0 / 16.0, 1.0 / 16.0, 9.0 / 16.0, +15.0 / 16.0, 7.0 / 16.0, 13.0 / 16.0, 5.0 / 16.0); + +#endif + +vec4 calculateFinalColor(vec4 color) { + #ifndef NO_OVERLAY + color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); + #endif + + #ifndef EMISSIVE + color *= lightMapColor; + #endif + + #ifdef GLINT + vec4 glintColor = GlintAlpha * texture(GlintSampler, texCoordGlint); + // Matches BlendFuntion.GLINT + color.rgb += glintColor.rgb * glintColor.rgb; + #endif + + #ifdef OIT_ACCUMULATE + color = sampleColorForAccumulation(color); + vec4 fogColor = vec4(FogColor.rgb * color.a, FogColor.a); + #else + vec4 fogColor = FogColor; + #endif + + return apply_fog(color, sphericalVertexDistance, cylindricalVertexDistance, FogEnvironmentalStart, FogEnvironmentalEnd, FogRenderDistanceStart, FogRenderDistanceEnd, fogColor); +} + +void main() { + vec4 color = texture(Sampler0, texCoord0); + + #ifdef OIT_ADDITIVE + color.a = min(0.99, color.a); + #endif + + #ifdef ALPHA_CUTOUT + if (color.a < ALPHA_CUTOUT) { + discard; + } + #endif + + #ifdef PER_FACE_LIGHTING + vec4 faceVertexColor = gl_FrontFacing ? vertexPerFaceColorFront : vertexPerFaceColorBack; + #else + vec4 faceVertexColor = vertexColor; + #endif + + #ifdef DISSOLVE + if (faceVertexColor.a < texture(DissolveMaskSampler, texCoord0).a) { + discard; + } + // The dissolve effect entirely replaces translucency + faceVertexColor.a = 1.0; + #endif + + color *= faceVertexColor * ColorModulator; + + #ifdef GLINT + color.a = max(color.a, GlintAlpha); + #endif + + #ifdef OIT_ALPHA_ONLY + executeAlphaOnlyPhase(gl_FragCoord.z, color.a); + #else + fragColor = calculateFinalColor(color); + + #if defined(MAYBE_PLAYERDISP) && !defined(OIT_ACCUMULATE) + if (part > 1.0 - 10e-6 && fragColor.a < 1.0) { + fragColor.a = max(fragColor.a, MINALPHA); + + vec3 underCol = texture(Sampler0, texCoord1).rgb; + vec3 trueMix = mix(underCol, fragColor.rgb, fragColor.a); + float fade = mix(fragColor.a, 1.0, clamp((cylindricalVertexDistance - FADEBIAS) / (FADERANGE - FADEBIAS), 0.0, 1.0)); + + fragColor = vec4((trueMix - (1 - fade) * underCol) / fade, fade); + if (fragColor.a < bayer4[int(gl_FragCoord.x) % 4][int(gl_FragCoord.y) % 4] + (0.5 / 16.0)) { + discard; + } + else { + fragColor.a = 1.0; + } + } + #endif + #endif +} diff --git a/core/src/main/resources/pack/assets/minecraft/shaders/core/entity.vsh b/core/src/main/resources/pack/assets/minecraft/shaders/core/entity.vsh new file mode 100644 index 0000000..7288c1e --- /dev/null +++ b/core/src/main/resources/pack/assets/minecraft/shaders/core/entity.vsh @@ -0,0 +1,258 @@ +#version 330 +#extension GL_ARB_separate_shader_objects : require + +#if defined(PER_FACE_LIGHTING) || !defined(NO_CARDINAL_LIGHTING) +#include +#endif +#include +#include +#include +#include + +#if defined(ALPHA_CUTOUT) && !defined(EMISSIVE) && !defined(NO_OVERLAY) && !defined(APPLY_TEXTURE_MATRIX) +#define MAYBE_PLAYERDISP 1 +#endif + +#define SPLITMODEL 0 + +layout(location = 0) in vec3 Position; +layout(location = 1) in vec4 Color; +layout(location = 2) in vec2 UV0; +layout(location = 3) in ivec2 UV1; +layout(location = 4) in ivec2 UV2; +layout(location = 5) in vec3 Normal; + +#ifdef MAYBE_PLAYERDISP +uniform sampler2D Sampler0; +#endif + +#if !defined(NO_OVERLAY) && !defined(OIT_ALPHA_ONLY) +uniform sampler2D Sampler1; +#endif + +#if !defined(EMISSIVE) && !defined(OIT_ALPHA_ONLY) +uniform sampler2D Sampler2; +#endif + +layout(location = 0) out float sphericalVertexDistance; +layout(location = 1) out float cylindricalVertexDistance; + +#ifdef PER_FACE_LIGHTING +layout(location = 2) out vec4 vertexPerFaceColorBack; +layout(location = 3) out vec4 vertexPerFaceColorFront; +#else +layout(location = 2) out vec4 vertexColor; +#endif + +#ifndef EMISSIVE +layout(location = 4) out vec4 lightMapColor; +#endif + +#ifndef NO_OVERLAY +layout(location = 5) out vec4 overlayColor; +#endif + +layout(location = 6) out vec2 texCoord0; +#ifdef GLINT +layout(location = 7) out vec2 texCoordGlint; +#endif + +#ifdef MAYBE_PLAYERDISP +layout(location = 8) out vec2 texCoord1; +layout(location = 9) out float part; + +#define SPACING 1024.0 +#define MAXRANGE (0.5 * SPACING) +#define SKINRES 64 +#define FACERES 8 + +#define SLIMCHECK0 vec2(54.0 / float(SKINRES), 20.0 / float(SKINRES)) +#define SLIMCHECK1 vec2(55.0 / float(SKINRES), 20.0 / float(SKINRES)) + +const vec4[] subuvs = vec4[]( +vec4(4.0, 0.0, 8.0, 4.0 ), // 4x4x12 +vec4(8.0, 0.0, 12.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 8.0, 16.0), +vec4(8.0, 4.0, 12.0, 16.0), +vec4(12.0, 4.0, 16.0, 16.0), +vec4(4.0, 0.0, 7.0, 4.0 ), // 4x3x12 +vec4(7.0, 0.0, 10.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 7.0, 16.0), +vec4(7.0, 4.0, 11.0, 16.0), +vec4(11.0, 4.0, 14.0, 16.0), +vec4(4.0, 0.0, 12.0, 4.0 ), // 4x8x12 +vec4(12.0, 0.0, 20.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 12.0, 16.0), +vec4(12.0, 4.0, 16.0, 16.0), +vec4(16.0, 4.0, 24.0, 16.0) +); + +const vec2[] origins = vec2[]( +vec2(40.0, 16.0), // right arm +vec2(40.0, 32.0), +vec2(32.0, 48.0), // left arm +vec2(48.0, 48.0), +vec2(40.0, 16.0), // slim right arm +vec2(40.0, 32.0), +vec2(32.0, 48.0), // slim left arm +vec2(48.0, 48.0), +vec2(16.0, 16.0), // torso +vec2(16.0, 32.0), +vec2(0.0, 16.0), // right leg +vec2(0.0, 32.0), +vec2(16.0, 48.0), // left leg +vec2(0.0, 48.0) +); + +const int[] faceremap = int[](0, 0, 1, 1, 2, 3, 4, 5); +#endif + +void main() { + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); + + sphericalVertexDistance = fog_spherical_distance(Position); + cylindricalVertexDistance = fog_cylindrical_distance(Position); + +#ifdef PER_FACE_LIGHTING + vec2 light = minecraft_compute_light(Light0_Direction, Light1_Direction, Normal); + vertexPerFaceColorBack = minecraft_mix_light_separate(-light, Color); + vertexPerFaceColorFront = minecraft_mix_light_separate(light, Color); +#elif defined(NO_CARDINAL_LIGHTING) + vertexColor = Color; +#else + vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); +#endif + +#if !defined(EMISSIVE) && !defined(OIT_ALPHA_ONLY) + lightMapColor = sample_lightmap(Sampler2, UV2); +#endif + +#if !defined(NO_OVERLAY) && !defined(OIT_ALPHA_ONLY) + overlayColor = texelFetch(Sampler1, UV1, 0); +#endif + + texCoord0 = UV0; + +#ifdef APPLY_TEXTURE_MATRIX + texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; +#endif + +#ifdef GLINT + texCoordGlint = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; +#endif + +#ifdef MAYBE_PLAYERDISP + ivec2 dim = textureSize(Sampler0, 0); + part = 0.0; + texCoord1 = vec2(0.0); + + // check world projmat (not gui), 64x64 texture (player tex dim), valid fog (not hand) + if (abs(ProjMat[2][3]) > 10e-6 && dim.x == SKINRES && dim.y == SKINRES && FogRenderDistanceEnd > FogRenderDistanceStart) { + int partId = -int((Position.y - MAXRANGE) / SPACING); + + part = float(partId); + + if (partId != 0) { + partId -= 1; + // vec4 samp1 = texture(Sampler0, SLIMCHECK0); + // vec4 samp2 = texture(Sampler0, SLIMCHECK1); + bool slim = partId == 2 || partId == 3; //samp1.a == 0.0 || (((samp1.r + samp1.g + samp1.b) == 0.0) && ((samp2.r + samp2.g + samp2.b) == 0.0) && samp1.a == 1.0 && samp2.a == 1.0); + int partIdMod = partId % 7; + int outerLayer = (gl_VertexIndex / 24) % 2; + int vertexId = gl_VertexIndex % 4; + int faceId = (gl_VertexIndex % 24) / 4; + ivec2 faceIdTmp = ivec2(round(UV0 * SKINRES)); + + // find the desired part UV origin + vec2 UVout = origins[2 * partIdMod + outerLayer]; + vec2 UVout2 = origins[2 * partIdMod]; + + // find the player head face UV origin + if ((faceId != 1 && vertexId >= 2) || (faceId == 1 && vertexId <= 1)) { + faceIdTmp.y -= FACERES; + } + if (vertexId == 0 || vertexId == 3) { + faceIdTmp.x -= FACERES; + } + + // calculate a faceId based on face UV origin + faceIdTmp /= FACERES; + faceId = (faceIdTmp.x % 4) + 4 * faceIdTmp.y; + faceId = faceremap[faceId]; + int subuvIndex = faceId; + + if (slim) { // select slim arms + subuvIndex += 6; + } + else if (partIdMod == 4) { // select torso + subuvIndex += 12; + } + + vec4 subuv = subuvs[subuvIndex]; + vec2 offset = vec2(0.0); + + #if SPLITMODEL == 1 + // adjust UVs in split cases + if (faceId >= 2) { + subuv.w -= 6.0; + if (partId >= 5) { + subuv.yw += 6.0; + } + } + #endif + + // find the UV offset within the current part + if (faceId == 1) { + if (vertexId == 0) { + offset += subuv.zw; + } + else if (vertexId == 1) { + offset += subuv.xw; + } + else if (vertexId == 2) { + offset += subuv.xy; + } + else { + offset += subuv.zy; + } + } + else { + if (vertexId == 0) { + offset += subuv.zy; + } + else if (vertexId == 1) { + offset += subuv.xy; + } + else if (vertexId == 2) { + offset += subuv.xw; + } + else { + offset += subuv.zw; + } + } + + // apply offset to part origin and normalize + UVout += offset; + UVout2 += offset; + UVout /= float(SKINRES); + UVout2 /= float(SKINRES); + + // assign output + vec3 wpos = Position; + wpos.y += SPACING * (partId + 1); + gl_Position = ProjMat * ModelViewMat * vec4(wpos, 1.0); + + sphericalVertexDistance = fog_spherical_distance(wpos); + cylindricalVertexDistance = fog_cylindrical_distance(wpos); + + texCoord0 = UVout; + texCoord1 = UVout2; + + return; + } + } +#endif +} diff --git a/core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.fsh b/core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.fsh new file mode 100644 index 0000000..8e90554 --- /dev/null +++ b/core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.fsh @@ -0,0 +1,47 @@ +#version 150 + +#moj_import + +uniform sampler2D Sampler0; + +uniform mat4 ModelViewMat; +uniform mat4 ProjMat; +uniform mat3 IViewRotMat; + +uniform vec4 ColorModulator; +uniform float FogStart; +uniform float FogEnd; +uniform vec4 FogColor; + +in float vertexDistance; +in vec4 vertexColor; +in vec4 lightMapColor; +in vec4 overlayColor; +in vec2 texCoord0; +in vec2 texCoord1; +in vec4 normal; +in float part; + +out vec4 fragColor; + +void main() { + vec4 color = texture(Sampler0, texCoord0); + if (color.a < 0.1 || abs(mod(part + 0.5, 1.0) - 0.5) > 0.001) { + discard; + } + if (color.a < 1.0 && part > 0.5) { + vec4 color2 = texture(Sampler0, texCoord1); + if (color.a < 0.75 && int(gl_FragCoord.x + gl_FragCoord.y) % 2 == 0) { + discard; + } + else { + color.rgb = mix(color2.rgb, color.rgb, min(1.0, color.a * 2)); + color.a = 1.0; + } + } + + color *= vertexColor * ColorModulator; + color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); + color *= lightMapColor; + fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); +} diff --git a/core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.json b/core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.json new file mode 100644 index 0000000..708c341 --- /dev/null +++ b/core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.json @@ -0,0 +1,34 @@ +{ + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "rendertype_entity_translucent", + "fragment": "rendertype_entity_translucent", + "attributes": [ + "Position", + "Color", + "UV0", + "UV1", + "UV2", + "Normal" + ], + "samplers": [ + { "name": "Sampler0" }, + { "name": "Sampler1" }, + { "name": "Sampler2" } + ], + "uniforms": [ + { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "IViewRotMat", "type": "matrix3x3", "count": 9, "values": [ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, + { "name": "Light0_Direction", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] }, + { "name": "Light1_Direction", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] }, + { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogColor", "type": "float", "count": 4,"values": [ 0.0, 0.0, 0.0, 0.0 ]}, + { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } + ] +} diff --git a/core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.vsh b/core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.vsh new file mode 100644 index 0000000..5e8d802 --- /dev/null +++ b/core/src/main/resources/pack/assets/minecraft/shaders/core/rendertype_entity_translucent.vsh @@ -0,0 +1,205 @@ +#version 150 + +#moj_import +#moj_import +#moj_import + +in vec3 Position; +in vec4 Color; +in vec2 UV0; +in ivec2 UV1; +in ivec2 UV2; +in vec3 Normal; + +uniform sampler2D Sampler0; +uniform sampler2D Sampler1; +uniform sampler2D Sampler2; + +uniform mat4 ModelViewMat; +uniform mat4 ProjMat; +uniform mat3 IViewRotMat; +uniform int FogShape; + +uniform vec3 Light0_Direction; +uniform vec3 Light1_Direction; + + +out float vertexDistance; +out vec4 vertexColor; +out vec4 lightMapColor; +out vec4 overlayColor; +out vec2 texCoord0; +out vec2 texCoord1; +out vec4 normal; +out float part; + +#define SPACING 1024.0 +#define MAXRANGE (0.5 * SPACING) + +const ivec2[] vanillaUVs = ivec2[]( + ivec2(8, 0), // Top + ivec2(16, 0), // Bottom + ivec2(0, 8), // Right + ivec2(8, 8), // Front + ivec2(16, 8), // Left + ivec2(24, 8) // Back +); + +const vec4[] subuvs = vec4[]( + // 4x4x12 + vec4(4.0, 0.0, 8.0, 4.0 ), // Top + vec4(8.0, 0.0, 12.0, 4.0 ), // Bottom + vec4(0.0, 4.0, 4.0, 16.0), // Right + vec4(4.0, 4.0, 8.0, 16.0), // Front + vec4(8.0, 4.0, 12.0, 16.0), // Left + vec4(12.0, 4.0, 16.0, 16.0), // Back + + // 4x3x12 + vec4(4.0, 0.0, 7.0, 4.0 ), + vec4(7.0, 0.0, 10.0, 4.0 ), + vec4(0.0, 4.0, 4.0, 16.0), + vec4(4.0, 4.0, 7.0, 16.0), + vec4(7.0, 4.0, 11.0, 16.0), + vec4(11.0, 4.0, 14.0, 16.0), + + // 4x8x12 + vec4(4.0, 0.0, 12.0, 4.0 ), + vec4(12.0, 0.0, 20.0, 4.0 ), + vec4(0.0, 4.0, 4.0, 16.0), + vec4(4.0, 4.0, 12.0, 16.0), + vec4(12.0, 4.0, 16.0, 16.0), + vec4(16.0, 4.0, 24.0, 16.0) +); + +const vec2[] origins = vec2[]( + vec2(40.0, 16.0), // right arm + vec2(40.0, 32.0), + vec2(32.0, 48.0), // left arm + vec2(48.0, 48.0), + vec2(40.0, 16.0), // slim right arm + vec2(40.0, 32.0), + vec2(32.0, 48.0), // slim left arm + vec2(48.0, 48.0), + vec2(16.0, 16.0), // torso + vec2(16.0, 32.0), + vec2(0.0, 16.0), // right leg + vec2(0.0, 32.0), + vec2(16.0, 48.0), // left leg + vec2(0.0, 48.0) +); + +// face remap +const int[] sodium = int[](0, 1, 3, 5, 4, 2); + +int remapFace(int id, bool hat) { + int face = (id / 4) % 6; + int sodiumFace = sodium[face]; + if(face == sodiumFace) + return face; + + int u = int(UV0.x * 64); + int v = int(UV0.y * 64); + int localId = id % 4; + switch(localId) { + case 0: + u -= 8; + break; + case 1: + break; + case 2: + v -= 8; + break; + case 3: + u -= 8; + v -= 8; + break; + } + + if(hat) + u -= 32; + + ivec2 vanilla = vanillaUVs[face]; + return vanilla.x == u && vanilla.y == v ? face : sodiumFace; +} + +int subUVOffset(int partId) { + if (partId == 3 || partId == 4) // Check for slim left or right arm + return 6; + if (partId == 5) // Check for body part + return 12; + return 0; +} + +vec2 createOffset(int faceId, int vertexId, vec4 subuv) { + vec2 offset = vec2(0.0); + if (faceId == 1) { + if (vertexId == 0) { + offset += subuv.zw; + } else if (vertexId == 1) { + offset += subuv.xw; + } else if (vertexId == 2) { + offset += subuv.xy; + } else { + offset += subuv.zy; + } + } else { + if (vertexId == 0) { + offset += subuv.zy; + } else if (vertexId == 1) { + offset += subuv.xy; + } else if (vertexId == 2) { + offset += subuv.xw; + } else { + offset += subuv.zw; + } + } + return offset; +} + +void main() { + vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, normalize(Normal), Color); + lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); + overlayColor = texelFetch(Sampler1, UV1, 0); + normal = ProjMat * ModelViewMat * vec4(Normal, 0.0); + + ivec2 dim = textureSize(Sampler0, 0); + + if (ProjMat[2][3] == 0.0 || dim.x != 64 || dim.y != 64) { // short circuit if cannot be player + part = 0.0; + texCoord0 = UV0; + texCoord1 = vec2(0.0); + vertexDistance = stable_fog_distance(ModelViewMat, IViewRotMat * Position, FogShape); + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); + } else { + vec3 wpos = IViewRotMat * Position; + vec2 UVout = UV0; + vec2 UVout2 = vec2(0.0); + int partId = -int((wpos.y - MAXRANGE) / SPACING); + part = float(partId); + + if (partId == 0) { // higher precision position if no translation is needed + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); + } else { + int hatLayer = (gl_VertexID / 24) % 2; + int face = remapFace(gl_VertexID % 48, hatLayer == 1) % 6; + + UVout = origins[2 * (partId - 1) + hatLayer]; + UVout2 = origins[2 * (partId - 1)]; + + vec4 subuv = subuvs[subUVOffset(partId) + face]; + vec2 offset = createOffset(face, gl_VertexID % 4, subuv); + + UVout += offset; + UVout2 += offset; + UVout /= 64.0; + UVout2 /= 64.0; + + wpos.y += SPACING * partId; + gl_Position = ProjMat * ModelViewMat * vec4(inverse(IViewRotMat) * wpos, 1.0); + } + + vertexDistance = stable_fog_distance(ModelViewMat, wpos, FogShape); + texCoord0 = UVout; + texCoord1 = UVout2; + } +} \ No newline at end of file diff --git a/core/src/main/resources/pack/assets/minecraft/shaders/include/player_shader.glsl b/core/src/main/resources/pack/assets/minecraft/shaders/include/player_shader.glsl new file mode 100644 index 0000000..908eadf --- /dev/null +++ b/core/src/main/resources/pack/assets/minecraft/shaders/include/player_shader.glsl @@ -0,0 +1,11 @@ +#version 150 + +float stable_fog_distance(mat4 modelViewMat, vec3 pos, int shape) { + if (shape == 0) { + return length((modelViewMat * vec4(pos, 1.0)).xyz); + } else { + float distXZ = length((modelViewMat * vec4(pos.x, 0.0, pos.z, 1.0)).xyz); + float distY = length((modelViewMat * vec4(0.0, pos.y, 0.0, 1.0)).xyz); + return max(distXZ, distY); + } +} \ No newline at end of file diff --git a/core/src/main/resources/pack/assets/modelengine/items/player_head.json b/core/src/main/resources/pack/assets/modelengine/items/player_head.json new file mode 100644 index 0000000..0ce139b --- /dev/null +++ b/core/src/main/resources/pack/assets/modelengine/items/player_head.json @@ -0,0 +1,119 @@ +{ + "model": { + "type": "minecraft:range_dispatch", + "entries": [ + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/head", + "model": { + "type": "minecraft:player_head" + } + }, + "threshold": 1 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/right_arm", + "model": { + "type": "minecraft:player_head" + } + }, + "threshold": 2 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/left_arm", + "model": { + "type": "minecraft:player_head" + } + }, + "threshold": 3 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/torso", + "model": { + "type": "minecraft:player_head" + } + }, + "threshold": 4 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/right_leg", + "model": { + "type": "minecraft:player_head" + } + }, + "threshold": 5 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/left_leg", + "model": { + "type": "minecraft:player_head" + } + }, + "threshold": 6 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/slim_right", + "model": { + "type": "minecraft:player_head" + } + }, + "threshold": 7 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/slim_left", + "model": { + "type": "minecraft:player_head" + } + }, + "threshold": 8 + } + ], + "fallback": { + "type": "minecraft:special", + "base": "minecraft:item/template_skull", + "model": { + "type": "minecraft:player_head" + } + }, + "property": "minecraft:custom_model_data", + "transformation": { + "left_rotation": [ + 1.0, + 0.0, + 0.0, + -0.0 + ], + "right_rotation": [ + 0.0, + 0.0, + 0.0, + 1.0 + ], + "scale": [ + 1.0, + 1.0, + 1.0 + ], + "translation": [ + 0.5, + 0.0, + 0.5 + ] + } + } +} \ No newline at end of file diff --git a/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/head.json b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/head.json new file mode 100644 index 0000000..7c30eee --- /dev/null +++ b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/head.json @@ -0,0 +1 @@ +{"parent":"builtin/entity","display":{"thirdperson_righthand":{"rotation":[0,180,0],"translation":[0,7.5,0],"scale":[0.9375,0.9375,0.9375]}}} \ No newline at end of file diff --git a/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/left_arm.json b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/left_arm.json new file mode 100644 index 0000000..750991e --- /dev/null +++ b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/left_arm.json @@ -0,0 +1 @@ +{"parent":"builtin/entity","display":{"thirdperson_righthand":{"rotation":[0,180,0],"translation":[-0.9375,1.875,0],"scale":[0.46875,1.40625,0.46875]}}} \ No newline at end of file diff --git a/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/left_leg.json b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/left_leg.json new file mode 100644 index 0000000..bfd59e2 --- /dev/null +++ b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/left_leg.json @@ -0,0 +1 @@ +{"parent":"builtin/entity","display":{"thirdperson_righthand":{"rotation":[0,180,0],"translation":[0,0,0],"scale":[0.46875,1.40625,0.46875]}}} \ No newline at end of file diff --git a/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/right_arm.json b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/right_arm.json new file mode 100644 index 0000000..886f3af --- /dev/null +++ b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/right_arm.json @@ -0,0 +1 @@ +{"parent":"builtin/entity","display":{"thirdperson_righthand":{"rotation":[0,180,0],"translation":[0.9375,1.875,0],"scale":[0.46875,1.40625,0.46875]}}} \ No newline at end of file diff --git a/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/right_leg.json b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/right_leg.json new file mode 100644 index 0000000..bfd59e2 --- /dev/null +++ b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/right_leg.json @@ -0,0 +1 @@ +{"parent":"builtin/entity","display":{"thirdperson_righthand":{"rotation":[0,180,0],"translation":[0,0,0],"scale":[0.46875,1.40625,0.46875]}}} \ No newline at end of file diff --git a/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/slim_left.json b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/slim_left.json new file mode 100644 index 0000000..1adccd1 --- /dev/null +++ b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/slim_left.json @@ -0,0 +1 @@ +{"parent":"builtin/entity","display":{"thirdperson_righthand":{"rotation":[0,180,0],"translation":[-0.46875,1.875,0],"scale":[0.3515625, 1.40625, 0.46875]}}} \ No newline at end of file diff --git a/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/slim_right.json b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/slim_right.json new file mode 100644 index 0000000..2327d8a --- /dev/null +++ b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/slim_right.json @@ -0,0 +1 @@ +{"parent":"builtin/entity","display":{"thirdperson_righthand":{"rotation":[0,180,0],"translation":[0.46875,1.875,0],"scale":[0.3515625, 1.40625, 0.46875]}}} \ No newline at end of file diff --git a/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/torso.json b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/torso.json new file mode 100644 index 0000000..b09d0a3 --- /dev/null +++ b/core/src/main/resources/pack/assets/modelengine/models/custom/entities/player/torso.json @@ -0,0 +1 @@ +{"parent":"builtin/entity","display":{"thirdperson_righthand":{"rotation":[0,180,0],"translation":[0,0,0],"scale":[0.9375,1.40625,0.46875]}}} \ No newline at end of file diff --git a/core/src/main/resources/pack/colorable/filled_map.json b/core/src/main/resources/pack/colorable/filled_map.json new file mode 100644 index 0000000..077d253 --- /dev/null +++ b/core/src/main/resources/pack/colorable/filled_map.json @@ -0,0 +1,7 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "item/filled_map", + "layer1": "item/filled_map_markings" + } +} diff --git a/core/src/main/resources/pack/colorable/leather_boots.json b/core/src/main/resources/pack/colorable/leather_boots.json new file mode 100644 index 0000000..9a9733a --- /dev/null +++ b/core/src/main/resources/pack/colorable/leather_boots.json @@ -0,0 +1,7 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "item/leather_boots", + "layer1": "item/leather_boots_overlay" + } +} diff --git a/core/src/main/resources/pack/colorable/leather_chestplate.json b/core/src/main/resources/pack/colorable/leather_chestplate.json new file mode 100644 index 0000000..45359b7 --- /dev/null +++ b/core/src/main/resources/pack/colorable/leather_chestplate.json @@ -0,0 +1,7 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "item/leather_chestplate", + "layer1": "item/leather_chestplate_overlay" + } +} diff --git a/core/src/main/resources/pack/colorable/leather_horse_armor.json b/core/src/main/resources/pack/colorable/leather_horse_armor.json new file mode 100644 index 0000000..9f74eff --- /dev/null +++ b/core/src/main/resources/pack/colorable/leather_horse_armor.json @@ -0,0 +1,7 @@ +{ + "parent": "minecraft:item/generated", + "textures": { + "layer0": "minecraft:item/leather_horse_armor", + "layer1": "minecraft:item/leather_horse_armor_overlay" + } +} \ No newline at end of file diff --git a/core/src/main/resources/pack/colorable/leather_leggings.json b/core/src/main/resources/pack/colorable/leather_leggings.json new file mode 100644 index 0000000..1d8f984 --- /dev/null +++ b/core/src/main/resources/pack/colorable/leather_leggings.json @@ -0,0 +1,7 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "item/leather_leggings", + "layer1": "item/leather_leggings_overlay" + } +} diff --git a/core/src/main/resources/pack/colorable/lingering_potion.json b/core/src/main/resources/pack/colorable/lingering_potion.json new file mode 100644 index 0000000..35ce5d7 --- /dev/null +++ b/core/src/main/resources/pack/colorable/lingering_potion.json @@ -0,0 +1,7 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "item/potion_overlay", + "layer1": "item/lingering_potion" + } +} diff --git a/core/src/main/resources/pack/colorable/potion.json b/core/src/main/resources/pack/colorable/potion.json new file mode 100644 index 0000000..73c2a57 --- /dev/null +++ b/core/src/main/resources/pack/colorable/potion.json @@ -0,0 +1,7 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "item/potion_overlay", + "layer1": "item/potion" + } +} diff --git a/core/src/main/resources/pack/colorable/splash_potion.json b/core/src/main/resources/pack/colorable/splash_potion.json new file mode 100644 index 0000000..d9aaa6b --- /dev/null +++ b/core/src/main/resources/pack/colorable/splash_potion.json @@ -0,0 +1,7 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "item/potion_overlay", + "layer1": "item/splash_potion" + } +} diff --git a/core/src/main/resources/pack/colorable/tipped_arrow.json b/core/src/main/resources/pack/colorable/tipped_arrow.json new file mode 100644 index 0000000..578defe --- /dev/null +++ b/core/src/main/resources/pack/colorable/tipped_arrow.json @@ -0,0 +1,7 @@ +{ + "parent": "item/generated", + "textures": { + "layer0": "item/tipped_arrow_head", + "layer1": "item/tipped_arrow_base" + } +} diff --git a/core/src/main/resources/pack/modelengine_1_19_4/assets/minecraft/models/item/player_head.json b/core/src/main/resources/pack/modelengine_1_19_4/assets/minecraft/models/item/player_head.json new file mode 100644 index 0000000..e3258b3 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_1_19_4/assets/minecraft/models/item/player_head.json @@ -0,0 +1,13 @@ +{ + "parent":"minecraft:item/template_skull", + "overrides":[ + {"predicate":{"custom_model_data":1},"model":"modelengine:custom/entities/player/head"}, + {"predicate":{"custom_model_data":2},"model":"modelengine:custom/entities/player/right_arm"}, + {"predicate":{"custom_model_data":3},"model":"modelengine:custom/entities/player/left_arm"}, + {"predicate":{"custom_model_data":4},"model":"modelengine:custom/entities/player/torso"}, + {"predicate":{"custom_model_data":5},"model":"modelengine:custom/entities/player/right_leg"}, + {"predicate":{"custom_model_data":6},"model":"modelengine:custom/entities/player/left_leg"}, + {"predicate":{"custom_model_data":7},"model":"modelengine:custom/entities/player/slim_right"}, + {"predicate":{"custom_model_data":8},"model":"modelengine:custom/entities/player/slim_left"} + ] +} \ No newline at end of file diff --git a/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/entity.fsh b/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/entity.fsh new file mode 100644 index 0000000..9ac7cb7 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/entity.fsh @@ -0,0 +1,35 @@ +#version 150 + +#moj_import + +uniform sampler2D Sampler0; + +uniform vec4 ColorModulator; +uniform float FogStart; +uniform float FogEnd; +uniform vec4 FogColor; + +in float vertexDistance; +in vec4 vertexColor; +in vec4 lightMapColor; +in vec4 overlayColor; +in vec2 texCoord0; + +out vec4 fragColor; + +void main() { + vec4 color = texture(Sampler0, texCoord0); +#ifdef ALPHA_CUTOUT + if (color.a < ALPHA_CUTOUT) { + discard; + } +#endif + color *= vertexColor * ColorModulator; +#ifndef NO_OVERLAY + color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); +#endif +#ifndef EMISSIVE + color *= lightMapColor; +#endif + fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); +} diff --git a/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/entity.vsh b/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/entity.vsh new file mode 100644 index 0000000..df60034 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/entity.vsh @@ -0,0 +1,46 @@ +#version 150 + +#moj_import +#moj_import + +in vec3 Position; +in vec4 Color; +in vec2 UV0; +in ivec2 UV1; +in ivec2 UV2; +in vec3 Normal; + +uniform sampler2D Sampler1; +uniform sampler2D Sampler2; + +uniform mat4 ModelViewMat; +uniform mat4 ProjMat; +uniform mat4 TextureMat; +uniform int FogShape; + +uniform vec3 Light0_Direction; +uniform vec3 Light1_Direction; + +out float vertexDistance; +out vec4 vertexColor; +out vec4 lightMapColor; +out vec4 overlayColor; +out vec2 texCoord0; + +void main() { + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); + + vertexDistance = fog_distance(Position, FogShape); +#ifdef NO_CARDINAL_LIGHTING + vertexColor = Color; +#else + vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); +#endif + lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); + overlayColor = texelFetch(Sampler1, UV1, 0); + + texCoord0 = UV0; +#ifdef APPLY_TEXTURE_MATRIX + texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; +#endif +} diff --git a/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.fsh b/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.fsh new file mode 100644 index 0000000..4d4d426 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.fsh @@ -0,0 +1,47 @@ +#version 150 + +#moj_import + +uniform sampler2D Sampler0; + +uniform mat4 ModelViewMat; +uniform mat4 ProjMat; +uniform mat3 IViewRotMat; + +uniform vec4 ColorModulator; +uniform float FogStart; +uniform float FogEnd; +uniform vec4 FogColor; + +in float vertexDistance; +in vec4 vertexColor; +in vec4 lightMapColor; +in vec4 overlayColor; +in vec2 texCoord0; +in vec2 texCoord1; +in vec4 normal; +in float part; + +out vec4 fragColor; + +void main() { + vec4 color = texture(Sampler0, texCoord0); + if (color.a < 0.1 || abs(mod(part + 0.5, 1.0) - 0.5) > 0.001) { + discard; + } + if (color.a < 1.0 && part > 0.5) { + vec4 color2 = texture(Sampler0, texCoord1); + if (color.a < 0.75 && int(gl_FragCoord.x + gl_FragCoord.y) % 2 == 0) { + discard; + } + else { + color.rgb = mix(color2.rgb, color.rgb, min(1.0, color.a * 2)); + color.a = 1.0; + } + } + + color *= vertexColor * ColorModulator; + color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); + color *= lightMapColor; + fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); +} diff --git a/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.json b/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.json new file mode 100644 index 0000000..f88f5bc --- /dev/null +++ b/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.json @@ -0,0 +1,34 @@ +{ + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "minecraft:core/rendertype_entity_translucent", + "fragment": "minecraft:core/rendertype_entity_translucent", + "attributes": [ + "Position", + "Color", + "UV0", + "UV1", + "UV2", + "Normal" + ], + "samplers": [ + { "name": "Sampler0" }, + { "name": "Sampler1" }, + { "name": "Sampler2" } + ], + "uniforms": [ + { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "IViewRotMat", "type": "matrix3x3", "count": 9, "values": [ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, + { "name": "Light0_Direction", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] }, + { "name": "Light1_Direction", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] }, + { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogColor", "type": "float", "count": 4,"values": [ 0.0, 0.0, 0.0, 0.0 ]}, + { "name": "FogShape", "type": "int", "count": 1, "values": [ 0 ] } + ] +} diff --git a/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.vsh b/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.vsh new file mode 100644 index 0000000..b4ab7bb --- /dev/null +++ b/core/src/main/resources/pack/modelengine_1_21_2/assets/minecraft/shaders/core/rendertype_entity_translucent.vsh @@ -0,0 +1,205 @@ +#version 150 + +#moj_import +#moj_import +#moj_import + +in vec3 Position; +in vec4 Color; +in vec2 UV0; +in ivec2 UV1; +in ivec2 UV2; +in vec3 Normal; + +uniform sampler2D Sampler0; +uniform sampler2D Sampler1; +uniform sampler2D Sampler2; + +uniform mat4 ModelViewMat; +uniform mat4 ProjMat; +uniform mat3 IViewRotMat; +uniform int FogShape; + +uniform vec3 Light0_Direction; +uniform vec3 Light1_Direction; + + +out float vertexDistance; +out vec4 vertexColor; +out vec4 lightMapColor; +out vec4 overlayColor; +out vec2 texCoord0; +out vec2 texCoord1; +out vec4 normal; +out float part; + +#define SPACING 1024.0 +#define MAXRANGE (0.5 * SPACING) + +const ivec2[] vanillaUVs = ivec2[]( + ivec2(8, 0), // Top + ivec2(16, 0), // Bottom + ivec2(0, 8), // Right + ivec2(8, 8), // Front + ivec2(16, 8), // Left + ivec2(24, 8) // Back +); + +const vec4[] subuvs = vec4[]( + // 4x4x12 + vec4(4.0, 0.0, 8.0, 4.0 ), // Top + vec4(8.0, 0.0, 12.0, 4.0 ), // Bottom + vec4(0.0, 4.0, 4.0, 16.0), // Right + vec4(4.0, 4.0, 8.0, 16.0), // Front + vec4(8.0, 4.0, 12.0, 16.0), // Left + vec4(12.0, 4.0, 16.0, 16.0), // Back + + // 4x3x12 + vec4(4.0, 0.0, 7.0, 4.0 ), + vec4(7.0, 0.0, 10.0, 4.0 ), + vec4(0.0, 4.0, 4.0, 16.0), + vec4(4.0, 4.0, 7.0, 16.0), + vec4(7.0, 4.0, 11.0, 16.0), + vec4(11.0, 4.0, 14.0, 16.0), + + // 4x8x12 + vec4(4.0, 0.0, 12.0, 4.0 ), + vec4(12.0, 0.0, 20.0, 4.0 ), + vec4(0.0, 4.0, 4.0, 16.0), + vec4(4.0, 4.0, 12.0, 16.0), + vec4(12.0, 4.0, 16.0, 16.0), + vec4(16.0, 4.0, 24.0, 16.0) +); + +const vec2[] origins = vec2[]( + vec2(40.0, 16.0), // right arm + vec2(40.0, 32.0), + vec2(32.0, 48.0), // left arm + vec2(48.0, 48.0), + vec2(40.0, 16.0), // slim right arm + vec2(40.0, 32.0), + vec2(32.0, 48.0), // slim left arm + vec2(48.0, 48.0), + vec2(16.0, 16.0), // torso + vec2(16.0, 32.0), + vec2(0.0, 16.0), // right leg + vec2(0.0, 32.0), + vec2(16.0, 48.0), // left leg + vec2(0.0, 48.0) +); + +// face remap +const int[] sodium = int[](0, 1, 3, 5, 4, 2); + +int remapFace(int id, bool hat) { + int face = (id / 4) % 6; + int sodiumFace = sodium[face]; + if(face == sodiumFace) + return face; + + int u = int(UV0.x * 64); + int v = int(UV0.y * 64); + int localId = id % 4; + switch(localId) { + case 0: + u -= 8; + break; + case 1: + break; + case 2: + v -= 8; + break; + case 3: + u -= 8; + v -= 8; + break; + } + + if(hat) + u -= 32; + + ivec2 vanilla = vanillaUVs[face]; + return vanilla.x == u && vanilla.y == v ? face : sodiumFace; +} + +int subUVOffset(int partId) { + if (partId == 3 || partId == 4) // Check for slim left or right arm + return 6; + if (partId == 5) // Check for body part + return 12; + return 0; +} + +vec2 createOffset(int faceId, int vertexId, vec4 subuv) { + vec2 offset = vec2(0.0); + if (faceId == 1) { + if (vertexId == 0) { + offset += subuv.zw; + } else if (vertexId == 1) { + offset += subuv.xw; + } else if (vertexId == 2) { + offset += subuv.xy; + } else { + offset += subuv.zy; + } + } else { + if (vertexId == 0) { + offset += subuv.zy; + } else if (vertexId == 1) { + offset += subuv.xy; + } else if (vertexId == 2) { + offset += subuv.xw; + } else { + offset += subuv.zw; + } + } + return offset; +} + +void main() { + vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, normalize(Normal), Color); + lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); + overlayColor = texelFetch(Sampler1, UV1, 0); + normal = ProjMat * ModelViewMat * vec4(Normal, 0.0); + + ivec2 dim = textureSize(Sampler0, 0); + + if (ProjMat[2][3] == 0.0 || dim.x != 64 || dim.y != 64) { // short circuit if cannot be player + part = 0.0; + texCoord0 = UV0; + texCoord1 = vec2(0.0); + vertexDistance = stable_fog_distance(ModelViewMat, IViewRotMat * Position, FogShape); + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); + } else { + vec3 wpos = IViewRotMat * Position; + vec2 UVout = UV0; + vec2 UVout2 = vec2(0.0); + int partId = -int((wpos.y - MAXRANGE) / SPACING); + part = float(partId); + + if (partId == 0) { // higher precision position if no translation is needed + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); + } else { + int hatLayer = (gl_VertexID / 24) % 2; + int face = remapFace(gl_VertexID % 48, hatLayer == 1) % 6; + + UVout = origins[2 * (partId - 1) + hatLayer]; + UVout2 = origins[2 * (partId - 1)]; + + vec4 subuv = subuvs[subUVOffset(partId) + face]; + vec2 offset = createOffset(face, gl_VertexID % 4, subuv); + + UVout += offset; + UVout2 += offset; + UVout /= 64.0; + UVout2 /= 64.0; + + wpos.y += SPACING * partId; + gl_Position = ProjMat * ModelViewMat * vec4(inverse(IViewRotMat) * wpos, 1.0); + } + + vertexDistance = stable_fog_distance(ModelViewMat, wpos, FogShape); + texCoord0 = UVout; + texCoord1 = UVout2; + } +} \ No newline at end of file diff --git a/core/src/main/resources/pack/modelengine_1_21_4/assets/modelengine/items/player_head.json b/core/src/main/resources/pack/modelengine_1_21_4/assets/modelengine/items/player_head.json new file mode 100644 index 0000000..5d44ec3 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_1_21_4/assets/modelengine/items/player_head.json @@ -0,0 +1,104 @@ +{ + "model": { + "type": "minecraft:range_dispatch", + "entries": [ + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/head", + "model": { + "type": "minecraft:head", + "kind": "player" + } + }, + "threshold": 1 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/right_arm", + "model": { + "type": "minecraft:head", + "kind": "player" + } + }, + "threshold": 2 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/left_arm", + "model": { + "type": "minecraft:head", + "kind": "player" + } + }, + "threshold": 3 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/torso", + "model": { + "type": "minecraft:head", + "kind": "player" + } + }, + "threshold": 4 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/right_leg", + "model": { + "type": "minecraft:head", + "kind": "player" + } + }, + "threshold": 5 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/left_leg", + "model": { + "type": "minecraft:head", + "kind": "player" + } + }, + "threshold": 6 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/slim_right", + "model": { + "type": "minecraft:head", + "kind": "player" + } + }, + "threshold": 7 + }, + { + "model": { + "type": "minecraft:special", + "base": "modelengine:custom/entities/player/slim_left", + "model": { + "type": "minecraft:head", + "kind": "player" + } + }, + "threshold": 8 + } + ], + "fallback": { + "type": "minecraft:special", + "base": "minecraft:item/template_skull", + "model": { + "type": "minecraft:head", + "kind": "player" + } + }, + "property": "minecraft:custom_model_data" + } +} \ No newline at end of file diff --git a/core/src/main/resources/pack/modelengine_1_21_5/assets/minecraft/shaders/core/entity.fsh b/core/src/main/resources/pack/modelengine_1_21_5/assets/minecraft/shaders/core/entity.fsh new file mode 100644 index 0000000..c8751e6 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_1_21_5/assets/minecraft/shaders/core/entity.fsh @@ -0,0 +1,73 @@ +#version 150 + +#moj_import + +#if defined(ALPHA_CUTOUT) && !defined(EMISSIVE) && !defined(NO_OVERLAY) && !defined(APPLY_TEXTURE_MATRIX) +#define MAYBE_PLAYERDISP 1 +#endif + +uniform sampler2D Sampler0; + +uniform mat4 ProjMat; + +uniform vec4 ColorModulator; +uniform float FogStart; +uniform float FogEnd; +uniform vec4 FogColor; + +in float vertexDistance; +in vec4 vertexColor; +in vec4 lightMapColor; +in vec4 overlayColor; +in vec2 texCoord0; +#ifdef MAYBE_PLAYERDISP +in vec2 texCoord1; +in float part; + +#define FADERANGE 12.0 +#define FADEBIAS 8.0 +#define MINALPHA 0.25 + +const mat4 bayer4 = mat4( 0.0 / 16.0, 8.0 / 16.0, 2.0 / 16.0, 10.0 / 16.0, + 12.0 / 16.0, 4.0 / 16.0, 14.0 / 16.0, 6.0 / 16.0, + 3.0 / 16.0, 11.0 / 16.0, 1.0 / 16.0, 9.0 / 16.0, + 15.0 / 16.0, 7.0 / 16.0, 13.0 / 16.0, 5.0 / 16.0); + +#endif + +out vec4 fragColor; + +void main() { + vec4 color = texture(Sampler0, texCoord0); +#ifdef ALPHA_CUTOUT + if (color.a < ALPHA_CUTOUT) { + discard; + } +#endif + color *= vertexColor * ColorModulator; +#ifndef NO_OVERLAY + color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); +#endif +#ifndef EMISSIVE + color *= lightMapColor; +#endif + fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); + +#ifdef MAYBE_PLAYERDISP + if (part > 1.0 - 10e-6 && fragColor.a < 1.0) { + fragColor.a = max(fragColor.a, MINALPHA); + + vec3 underCol = texture(Sampler0, texCoord1).rgb; + vec3 trueMix = mix(underCol, fragColor.rgb, fragColor.a); + float fade = mix(fragColor.a, 1.0, clamp((vertexDistance - FADEBIAS) / (FADERANGE - FADEBIAS), 0.0, 1.0)); + + fragColor = vec4((trueMix - (1 - fade) * underCol) / fade, fade); + if (fragColor.a < bayer4[int(gl_FragCoord.x) % 4][int(gl_FragCoord.y) % 4] + (0.5 / 16.0)) { + discard; + } + else { + fragColor.a = 1.0; + } + } +#endif +} diff --git a/core/src/main/resources/pack/modelengine_1_21_5/assets/minecraft/shaders/core/entity.vsh b/core/src/main/resources/pack/modelengine_1_21_5/assets/minecraft/shaders/core/entity.vsh new file mode 100644 index 0000000..99d8e63 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_1_21_5/assets/minecraft/shaders/core/entity.vsh @@ -0,0 +1,219 @@ +#version 150 + +#moj_import +#moj_import + +#if defined(ALPHA_CUTOUT) && !defined(EMISSIVE) && !defined(NO_OVERLAY) && !defined(APPLY_TEXTURE_MATRIX) +#define MAYBE_PLAYERDISP 1 +#endif + +#define SPLITMODEL 0 + +in vec3 Position; +in vec4 Color; +in vec2 UV0; +in ivec2 UV1; +in ivec2 UV2; +in vec3 Normal; + +#ifdef MAYBE_PLAYERDISP +uniform sampler2D Sampler0; +#endif +uniform sampler2D Sampler1; +uniform sampler2D Sampler2; + +uniform mat4 ModelViewMat; +uniform mat4 ProjMat; +uniform mat4 TextureMat; +uniform float FogStart; +uniform float FogEnd; +uniform int FogShape; + +uniform vec3 Light0_Direction; +uniform vec3 Light1_Direction; + +out float vertexDistance; +out vec4 vertexColor; +out vec4 lightMapColor; +out vec4 overlayColor; +out vec2 texCoord0; +#ifdef MAYBE_PLAYERDISP +out vec2 texCoord1; +out float part; + +#define SPACING 1024.0 +#define MAXRANGE (0.5 * SPACING) +#define SKINRES 64 +#define FACERES 8 + +#define SLIMCHECK0 vec2(54.0 / float(SKINRES), 20.0 / float(SKINRES)) +#define SLIMCHECK1 vec2(55.0 / float(SKINRES), 20.0 / float(SKINRES)) + +const vec4[] subuvs = vec4[]( + vec4(4.0, 0.0, 8.0, 4.0 ), // 4x4x12 + vec4(8.0, 0.0, 12.0, 4.0 ), + vec4(0.0, 4.0, 4.0, 16.0), + vec4(4.0, 4.0, 8.0, 16.0), + vec4(8.0, 4.0, 12.0, 16.0), + vec4(12.0, 4.0, 16.0, 16.0), + vec4(4.0, 0.0, 7.0, 4.0 ), // 4x3x12 + vec4(7.0, 0.0, 10.0, 4.0 ), + vec4(0.0, 4.0, 4.0, 16.0), + vec4(4.0, 4.0, 7.0, 16.0), + vec4(7.0, 4.0, 11.0, 16.0), + vec4(11.0, 4.0, 14.0, 16.0), + vec4(4.0, 0.0, 12.0, 4.0 ), // 4x8x12 + vec4(12.0, 0.0, 20.0, 4.0 ), + vec4(0.0, 4.0, 4.0, 16.0), + vec4(4.0, 4.0, 12.0, 16.0), + vec4(12.0, 4.0, 16.0, 16.0), + vec4(16.0, 4.0, 24.0, 16.0) +); + +const vec2[] origins = vec2[]( + vec2(40.0, 16.0), // right arm + vec2(40.0, 32.0), + vec2(32.0, 48.0), // left arm + vec2(48.0, 48.0), + vec2(40.0, 16.0), // slim right arm + vec2(40.0, 32.0), + vec2(32.0, 48.0), // slim left arm + vec2(48.0, 48.0), + vec2(16.0, 16.0), // torso + vec2(16.0, 32.0), + vec2(0.0, 16.0), // right leg + vec2(0.0, 32.0), + vec2(16.0, 48.0), // left leg + vec2(0.0, 48.0) +); + +const int[] faceremap = int[](0, 0, 1, 1, 2, 3, 4, 5); +#endif + +void main() { +#ifdef NO_CARDINAL_LIGHTING + vertexColor = Color; +#else + vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); +#endif + lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); + overlayColor = texelFetch(Sampler1, UV1, 0); + +#ifdef MAYBE_PLAYERDISP + ivec2 dim = textureSize(Sampler0, 0); + part = 0.0; + texCoord1 = vec2(0.0); + + // check world projmat (not gui), 64x64 texture (player tex dim), valid fog (not hand) + if (abs(ProjMat[2][3]) > 10e-6 && dim.x == SKINRES && dim.y == SKINRES && FogEnd > FogStart) { + int partId = -int((Position.y - MAXRANGE) / SPACING); + + part = float(partId); + + if (partId != 0) { + partId -= 1; + // vec4 samp1 = texture(Sampler0, SLIMCHECK0); + // vec4 samp2 = texture(Sampler0, SLIMCHECK1); + bool slim = partId == 2 || partId == 3; //samp1.a == 0.0 || (((samp1.r + samp1.g + samp1.b) == 0.0) && ((samp2.r + samp2.g + samp2.b) == 0.0) && samp1.a == 1.0 && samp2.a == 1.0); + int partIdMod = partId % 7; + int outerLayer = (gl_VertexID / 24) % 2; + int vertexId = gl_VertexID % 4; + int faceId = (gl_VertexID % 24) / 4; + ivec2 faceIdTmp = ivec2(round(UV0 * SKINRES)); + + // find the desired part UV origin + vec2 UVout = origins[2 * partIdMod + outerLayer]; + vec2 UVout2 = origins[2 * partIdMod]; + + // find the player head face UV origin + if ((faceId != 1 && vertexId >= 2) || (faceId == 1 && vertexId <= 1)) { + faceIdTmp.y -= FACERES; + } + if (vertexId == 0 || vertexId == 3) { + faceIdTmp.x -= FACERES; + } + + // calculate a faceId based on face UV origin + faceIdTmp /= FACERES; + faceId = (faceIdTmp.x % 4) + 4 * faceIdTmp.y; + faceId = faceremap[faceId]; + int subuvIndex = faceId; + + if (slim) { // select slim arms + subuvIndex += 6; + } + else if (partIdMod == 4) { // select torso + subuvIndex += 12; + } + + vec4 subuv = subuvs[subuvIndex]; + vec2 offset = vec2(0.0); + +#if SPLITMODEL == 1 + // adjust UVs in split cases + if (faceId >= 2) { + subuv.w -= 6.0; + if (partId >= 5) { + subuv.yw += 6.0; + } + } +#endif + + // find the UV offset within the current part + if (faceId == 1) { + if (vertexId == 0) { + offset += subuv.zw; + } + else if (vertexId == 1) { + offset += subuv.xw; + } + else if (vertexId == 2) { + offset += subuv.xy; + } + else { + offset += subuv.zy; + } + } + else { + if (vertexId == 0) { + offset += subuv.zy; + } + else if (vertexId == 1) { + offset += subuv.xy; + } + else if (vertexId == 2) { + offset += subuv.xw; + } + else { + offset += subuv.zw; + } + } + + // apply offset to part origin and normalize + UVout += offset; + UVout2 += offset; + UVout /= float(SKINRES); + UVout2 /= float(SKINRES); + + // assign output + vec3 wpos = Position; + wpos.y += SPACING * (partId + 1); + gl_Position = ProjMat * ModelViewMat * vec4(wpos, 1.0); + vertexDistance = fog_distance(wpos, FogShape); + texCoord0 = UVout; + texCoord1 = UVout2; + + return; + } + } +#endif + + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); + + vertexDistance = fog_distance(Position, FogShape); + + texCoord0 = UV0; +#ifdef APPLY_TEXTURE_MATRIX + texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; +#endif +} diff --git a/core/src/main/resources/pack/modelengine_1_21_6/assets/minecraft/shaders/core/entity.fsh b/core/src/main/resources/pack/modelengine_1_21_6/assets/minecraft/shaders/core/entity.fsh new file mode 100644 index 0000000..689af01 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_1_21_6/assets/minecraft/shaders/core/entity.fsh @@ -0,0 +1,68 @@ +#version 150 + +#moj_import +#moj_import + +#if defined(ALPHA_CUTOUT) && !defined(EMISSIVE) && !defined(NO_OVERLAY) && !defined(APPLY_TEXTURE_MATRIX) +#define MAYBE_PLAYERDISP 1 +#endif + +uniform sampler2D Sampler0; + +in float sphericalVertexDistance; +in float cylindricalVertexDistance; +in vec4 vertexColor; +in vec4 lightMapColor; +in vec4 overlayColor; +in vec2 texCoord0; +#ifdef MAYBE_PLAYERDISP +in vec2 texCoord1; +in float part; + +#define FADERANGE 12.0 +#define FADEBIAS 8.0 +#define MINALPHA 0.25 + +const mat4 bayer4 = mat4( 0.0 / 16.0, 8.0 / 16.0, 2.0 / 16.0, 10.0 / 16.0, +12.0 / 16.0, 4.0 / 16.0, 14.0 / 16.0, 6.0 / 16.0, +3.0 / 16.0, 11.0 / 16.0, 1.0 / 16.0, 9.0 / 16.0, +15.0 / 16.0, 7.0 / 16.0, 13.0 / 16.0, 5.0 / 16.0); + +#endif + +out vec4 fragColor; + +void main() { + vec4 color = texture(Sampler0, texCoord0); + #ifdef ALPHA_CUTOUT + if (color.a < ALPHA_CUTOUT) { + discard; + } + #endif + color *= vertexColor * ColorModulator; + #ifndef NO_OVERLAY + color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); + #endif + #ifndef EMISSIVE + color *= lightMapColor; + #endif + fragColor = apply_fog(color, sphericalVertexDistance, cylindricalVertexDistance, FogEnvironmentalStart, FogEnvironmentalEnd, FogRenderDistanceStart, FogRenderDistanceEnd, FogColor); + + #ifdef MAYBE_PLAYERDISP + if (part > 1.0 - 10e-6 && fragColor.a < 1.0) { + fragColor.a = max(fragColor.a, MINALPHA); + + vec3 underCol = texture(Sampler0, texCoord1).rgb; + vec3 trueMix = mix(underCol, fragColor.rgb, fragColor.a); + float fade = mix(fragColor.a, 1.0, clamp((cylindricalVertexDistance - FADEBIAS) / (FADERANGE - FADEBIAS), 0.0, 1.0)); + + fragColor = vec4((trueMix - (1 - fade) * underCol) / fade, fade); + if (fragColor.a < bayer4[int(gl_FragCoord.x) % 4][int(gl_FragCoord.y) % 4] + (0.5 / 16.0)) { + discard; + } + else { + fragColor.a = 1.0; + } + } + #endif +} \ No newline at end of file diff --git a/core/src/main/resources/pack/modelengine_1_21_6/assets/minecraft/shaders/core/entity.vsh b/core/src/main/resources/pack/modelengine_1_21_6/assets/minecraft/shaders/core/entity.vsh new file mode 100644 index 0000000..870dc72 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_1_21_6/assets/minecraft/shaders/core/entity.vsh @@ -0,0 +1,216 @@ +#version 150 + +#moj_import +#moj_import +#moj_import +#moj_import + +#if defined(ALPHA_CUTOUT) && !defined(EMISSIVE) && !defined(NO_OVERLAY) && !defined(APPLY_TEXTURE_MATRIX) +#define MAYBE_PLAYERDISP 1 +#endif + +#define SPLITMODEL 0 + +in vec3 Position; +in vec4 Color; +in vec2 UV0; +in ivec2 UV1; +in ivec2 UV2; +in vec3 Normal; + +#ifdef MAYBE_PLAYERDISP +uniform sampler2D Sampler0; +#endif +uniform sampler2D Sampler1; +uniform sampler2D Sampler2; + +out float sphericalVertexDistance; +out float cylindricalVertexDistance; +out vec4 vertexColor; +out vec4 lightMapColor; +out vec4 overlayColor; +out vec2 texCoord0; +#ifdef MAYBE_PLAYERDISP +out vec2 texCoord1; +out float part; + +#define SPACING 1024.0 +#define MAXRANGE (0.5 * SPACING) +#define SKINRES 64 +#define FACERES 8 + +#define SLIMCHECK0 vec2(54.0 / float(SKINRES), 20.0 / float(SKINRES)) +#define SLIMCHECK1 vec2(55.0 / float(SKINRES), 20.0 / float(SKINRES)) + +const vec4[] subuvs = vec4[]( +vec4(4.0, 0.0, 8.0, 4.0 ), // 4x4x12 +vec4(8.0, 0.0, 12.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 8.0, 16.0), +vec4(8.0, 4.0, 12.0, 16.0), +vec4(12.0, 4.0, 16.0, 16.0), +vec4(4.0, 0.0, 7.0, 4.0 ), // 4x3x12 +vec4(7.0, 0.0, 10.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 7.0, 16.0), +vec4(7.0, 4.0, 11.0, 16.0), +vec4(11.0, 4.0, 14.0, 16.0), +vec4(4.0, 0.0, 12.0, 4.0 ), // 4x8x12 +vec4(12.0, 0.0, 20.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 12.0, 16.0), +vec4(12.0, 4.0, 16.0, 16.0), +vec4(16.0, 4.0, 24.0, 16.0) +); + +const vec2[] origins = vec2[]( +vec2(40.0, 16.0), // right arm +vec2(40.0, 32.0), +vec2(32.0, 48.0), // left arm +vec2(48.0, 48.0), +vec2(40.0, 16.0), // slim right arm +vec2(40.0, 32.0), +vec2(32.0, 48.0), // slim left arm +vec2(48.0, 48.0), +vec2(16.0, 16.0), // torso +vec2(16.0, 32.0), +vec2(0.0, 16.0), // right leg +vec2(0.0, 32.0), +vec2(16.0, 48.0), // left leg +vec2(0.0, 48.0) +); + +const int[] faceremap = int[](0, 0, 1, 1, 2, 3, 4, 5); +#endif + +void main() { + #ifdef NO_CARDINAL_LIGHTING + vertexColor = Color; + #else + vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); + #endif + lightMapColor = texelFetch(Sampler2, UV2 / 16, 0); + overlayColor = texelFetch(Sampler1, UV1, 0); + + #ifdef MAYBE_PLAYERDISP + ivec2 dim = textureSize(Sampler0, 0); + part = 0.0; + texCoord1 = vec2(0.0); + + // check world projmat (not gui), 64x64 texture (player tex dim), valid fog (not hand) + if (abs(ProjMat[2][3]) > 10e-6 && dim.x == SKINRES && dim.y == SKINRES && FogRenderDistanceEnd > FogRenderDistanceStart) { + int partId = -int((Position.y - MAXRANGE) / SPACING); + + part = float(partId); + + if (partId != 0) { + partId -= 1; + // vec4 samp1 = texture(Sampler0, SLIMCHECK0); + // vec4 samp2 = texture(Sampler0, SLIMCHECK1); + bool slim = partId == 2 || partId == 3; //samp1.a == 0.0 || (((samp1.r + samp1.g + samp1.b) == 0.0) && ((samp2.r + samp2.g + samp2.b) == 0.0) && samp1.a == 1.0 && samp2.a == 1.0); + int partIdMod = partId % 7; + int outerLayer = (gl_VertexID / 24) % 2; + int vertexId = gl_VertexID % 4; + int faceId = (gl_VertexID % 24) / 4; + ivec2 faceIdTmp = ivec2(round(UV0 * SKINRES)); + + // find the desired part UV origin + vec2 UVout = origins[2 * partIdMod + outerLayer]; + vec2 UVout2 = origins[2 * partIdMod]; + + // find the player head face UV origin + if ((faceId != 1 && vertexId >= 2) || (faceId == 1 && vertexId <= 1)) { + faceIdTmp.y -= FACERES; + } + if (vertexId == 0 || vertexId == 3) { + faceIdTmp.x -= FACERES; + } + + // calculate a faceId based on face UV origin + faceIdTmp /= FACERES; + faceId = (faceIdTmp.x % 4) + 4 * faceIdTmp.y; + faceId = faceremap[faceId]; + int subuvIndex = faceId; + + if (slim) { // select slim arms + subuvIndex += 6; + } + else if (partIdMod == 4) { // select torso + subuvIndex += 12; + } + + vec4 subuv = subuvs[subuvIndex]; + vec2 offset = vec2(0.0); + + #if SPLITMODEL == 1 + // adjust UVs in split cases + if (faceId >= 2) { + subuv.w -= 6.0; + if (partId >= 5) { + subuv.yw += 6.0; + } + } + #endif + + // find the UV offset within the current part + if (faceId == 1) { + if (vertexId == 0) { + offset += subuv.zw; + } + else if (vertexId == 1) { + offset += subuv.xw; + } + else if (vertexId == 2) { + offset += subuv.xy; + } + else { + offset += subuv.zy; + } + } + else { + if (vertexId == 0) { + offset += subuv.zy; + } + else if (vertexId == 1) { + offset += subuv.xy; + } + else if (vertexId == 2) { + offset += subuv.xw; + } + else { + offset += subuv.zw; + } + } + + // apply offset to part origin and normalize + UVout += offset; + UVout2 += offset; + UVout /= float(SKINRES); + UVout2 /= float(SKINRES); + + // assign output + vec3 wpos = Position; + wpos.y += SPACING * (partId + 1); + gl_Position = ProjMat * ModelViewMat * vec4(wpos, 1.0); + + sphericalVertexDistance = fog_spherical_distance(wpos); + cylindricalVertexDistance = fog_cylindrical_distance(wpos); + + texCoord0 = UVout; + texCoord1 = UVout2; + + return; + } + } + #endif + + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); + + sphericalVertexDistance = fog_spherical_distance(Position); + cylindricalVertexDistance = fog_cylindrical_distance(Position); + + texCoord0 = UV0; + #ifdef APPLY_TEXTURE_MATRIX + texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; + #endif +} \ No newline at end of file diff --git a/core/src/main/resources/pack/modelengine_26_1/assets/minecraft/shaders/core/entity.fsh b/core/src/main/resources/pack/modelengine_26_1/assets/minecraft/shaders/core/entity.fsh new file mode 100644 index 0000000..84d2d69 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_26_1/assets/minecraft/shaders/core/entity.fsh @@ -0,0 +1,102 @@ +#version 330 + +#moj_import +#moj_import + +uniform sampler2D Sampler0; + +#if defined(ALPHA_CUTOUT) && !defined(EMISSIVE) && !defined(NO_OVERLAY) && !defined(APPLY_TEXTURE_MATRIX) +#define MAYBE_PLAYERDISP 1 +#endif + +#ifdef DISSOLVE +uniform sampler2D DissolveMaskSampler; +#endif + +in float sphericalVertexDistance; +in float cylindricalVertexDistance; + +#ifdef PER_FACE_LIGHTING +in vec4 vertexPerFaceColorBack; +in vec4 vertexPerFaceColorFront; +#else +in vec4 vertexColor; +#endif + +#ifndef EMISSIVE +in vec4 lightMapColor; +#endif + +#ifndef NO_OVERLAY +in vec4 overlayColor; +#endif + +in vec2 texCoord0; + +out vec4 fragColor; + +#ifdef MAYBE_PLAYERDISP +in vec2 texCoord1; +in float part; + +#define FADERANGE 12.0 +#define FADEBIAS 8.0 +#define MINALPHA 0.25 + +const mat4 bayer4 = mat4( 0.0 / 16.0, 8.0 / 16.0, 2.0 / 16.0, 10.0 / 16.0, +12.0 / 16.0, 4.0 / 16.0, 14.0 / 16.0, 6.0 / 16.0, +3.0 / 16.0, 11.0 / 16.0, 1.0 / 16.0, 9.0 / 16.0, +15.0 / 16.0, 7.0 / 16.0, 13.0 / 16.0, 5.0 / 16.0); + +#endif + +void main() { + vec4 color = texture(Sampler0, texCoord0); +#ifdef ALPHA_CUTOUT + if (color.a < ALPHA_CUTOUT) { + discard; + } +#endif + +#ifdef PER_FACE_LIGHTING + vec4 faceVertexColor = gl_FrontFacing ? vertexPerFaceColorFront : vertexPerFaceColorBack; +#else + vec4 faceVertexColor = vertexColor; +#endif + +#ifdef DISSOLVE + if (faceVertexColor.a < texture(DissolveMaskSampler, texCoord0).a) { + discard; + } + // The dissolve effect entirely replaces translucency + faceVertexColor.a = 1.0; +#endif + + color *= faceVertexColor * ColorModulator; +#ifndef NO_OVERLAY + color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); +#endif +#ifndef EMISSIVE + color *= lightMapColor; +#endif + + fragColor = apply_fog(color, sphericalVertexDistance, cylindricalVertexDistance, FogEnvironmentalStart, FogEnvironmentalEnd, FogRenderDistanceStart, FogRenderDistanceEnd, FogColor); + + #ifdef MAYBE_PLAYERDISP + if (part > 1.0 - 10e-6 && fragColor.a < 1.0) { + fragColor.a = max(fragColor.a, MINALPHA); + + vec3 underCol = texture(Sampler0, texCoord1).rgb; + vec3 trueMix = mix(underCol, fragColor.rgb, fragColor.a); + float fade = mix(fragColor.a, 1.0, clamp((cylindricalVertexDistance - FADEBIAS) / (FADERANGE - FADEBIAS), 0.0, 1.0)); + + fragColor = vec4((trueMix - (1 - fade) * underCol) / fade, fade); + if (fragColor.a < bayer4[int(gl_FragCoord.x) % 4][int(gl_FragCoord.y) % 4] + (0.5 / 16.0)) { + discard; + } + else { + fragColor.a = 1.0; + } + } + #endif +} diff --git a/core/src/main/resources/pack/modelengine_26_1/assets/minecraft/shaders/core/entity.vsh b/core/src/main/resources/pack/modelengine_26_1/assets/minecraft/shaders/core/entity.vsh new file mode 100644 index 0000000..0c8b211 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_26_1/assets/minecraft/shaders/core/entity.vsh @@ -0,0 +1,248 @@ +#version 330 + +#moj_import +#moj_import +#moj_import +#moj_import +#moj_import + +#if defined(ALPHA_CUTOUT) && !defined(EMISSIVE) && !defined(NO_OVERLAY) && !defined(APPLY_TEXTURE_MATRIX) +#define MAYBE_PLAYERDISP 1 +#endif + +#define SPLITMODEL 0 + +in vec3 Position; +in vec4 Color; +in vec2 UV0; +in ivec2 UV1; +in ivec2 UV2; +in vec3 Normal; + +#ifdef MAYBE_PLAYERDISP +uniform sampler2D Sampler0; +#endif + +#ifndef NO_OVERLAY +uniform sampler2D Sampler1; +#endif + +#ifndef EMISSIVE +uniform sampler2D Sampler2; +#endif + +out float sphericalVertexDistance; +out float cylindricalVertexDistance; + +#ifdef PER_FACE_LIGHTING +out vec4 vertexPerFaceColorBack; +out vec4 vertexPerFaceColorFront; +#else +out vec4 vertexColor; +#endif + +#ifndef EMISSIVE +out vec4 lightMapColor; +#endif + +#ifndef NO_OVERLAY +out vec4 overlayColor; +#endif + +out vec2 texCoord0; + +#ifdef MAYBE_PLAYERDISP +out vec2 texCoord1; +out float part; + +#define SPACING 1024.0 +#define MAXRANGE (0.5 * SPACING) +#define SKINRES 64 +#define FACERES 8 + +#define SLIMCHECK0 vec2(54.0 / float(SKINRES), 20.0 / float(SKINRES)) +#define SLIMCHECK1 vec2(55.0 / float(SKINRES), 20.0 / float(SKINRES)) + +const vec4[] subuvs = vec4[]( +vec4(4.0, 0.0, 8.0, 4.0 ), // 4x4x12 +vec4(8.0, 0.0, 12.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 8.0, 16.0), +vec4(8.0, 4.0, 12.0, 16.0), +vec4(12.0, 4.0, 16.0, 16.0), +vec4(4.0, 0.0, 7.0, 4.0 ), // 4x3x12 +vec4(7.0, 0.0, 10.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 7.0, 16.0), +vec4(7.0, 4.0, 11.0, 16.0), +vec4(11.0, 4.0, 14.0, 16.0), +vec4(4.0, 0.0, 12.0, 4.0 ), // 4x8x12 +vec4(12.0, 0.0, 20.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 12.0, 16.0), +vec4(12.0, 4.0, 16.0, 16.0), +vec4(16.0, 4.0, 24.0, 16.0) +); + +const vec2[] origins = vec2[]( +vec2(40.0, 16.0), // right arm +vec2(40.0, 32.0), +vec2(32.0, 48.0), // left arm +vec2(48.0, 48.0), +vec2(40.0, 16.0), // slim right arm +vec2(40.0, 32.0), +vec2(32.0, 48.0), // slim left arm +vec2(48.0, 48.0), +vec2(16.0, 16.0), // torso +vec2(16.0, 32.0), +vec2(0.0, 16.0), // right leg +vec2(0.0, 32.0), +vec2(16.0, 48.0), // left leg +vec2(0.0, 48.0) +); + +const int[] faceremap = int[](0, 0, 1, 1, 2, 3, 4, 5); +#endif + +void main() { + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); + + sphericalVertexDistance = fog_spherical_distance(Position); + cylindricalVertexDistance = fog_cylindrical_distance(Position); + +#ifdef PER_FACE_LIGHTING + vec2 light = minecraft_compute_light(Light0_Direction, Light1_Direction, Normal); + vertexPerFaceColorBack = minecraft_mix_light_separate(-light, Color); + vertexPerFaceColorFront = minecraft_mix_light_separate(light, Color); +#elif defined(NO_CARDINAL_LIGHTING) + vertexColor = Color; +#else + vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); +#endif + +#ifndef EMISSIVE + lightMapColor = sample_lightmap(Sampler2, UV2); +#endif + +#ifndef NO_OVERLAY + overlayColor = texelFetch(Sampler1, UV1, 0); +#endif + + texCoord0 = UV0; + +#ifdef APPLY_TEXTURE_MATRIX + texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; +#endif + +#ifdef MAYBE_PLAYERDISP + ivec2 dim = textureSize(Sampler0, 0); + part = 0.0; + texCoord1 = vec2(0.0); + + // check world projmat (not gui), 64x64 texture (player tex dim), valid fog (not hand) + if (abs(ProjMat[2][3]) > 10e-6 && dim.x == SKINRES && dim.y == SKINRES && FogRenderDistanceEnd > FogRenderDistanceStart) { + int partId = -int((Position.y - MAXRANGE) / SPACING); + + part = float(partId); + + if (partId != 0) { + partId -= 1; + // vec4 samp1 = texture(Sampler0, SLIMCHECK0); + // vec4 samp2 = texture(Sampler0, SLIMCHECK1); + bool slim = partId == 2 || partId == 3; //samp1.a == 0.0 || (((samp1.r + samp1.g + samp1.b) == 0.0) && ((samp2.r + samp2.g + samp2.b) == 0.0) && samp1.a == 1.0 && samp2.a == 1.0); + int partIdMod = partId % 7; + int outerLayer = (gl_VertexID / 24) % 2; + int vertexId = gl_VertexID % 4; + int faceId = (gl_VertexID % 24) / 4; + ivec2 faceIdTmp = ivec2(round(UV0 * SKINRES)); + + // find the desired part UV origin + vec2 UVout = origins[2 * partIdMod + outerLayer]; + vec2 UVout2 = origins[2 * partIdMod]; + + // find the player head face UV origin + if ((faceId != 1 && vertexId >= 2) || (faceId == 1 && vertexId <= 1)) { + faceIdTmp.y -= FACERES; + } + if (vertexId == 0 || vertexId == 3) { + faceIdTmp.x -= FACERES; + } + + // calculate a faceId based on face UV origin + faceIdTmp /= FACERES; + faceId = (faceIdTmp.x % 4) + 4 * faceIdTmp.y; + faceId = faceremap[faceId]; + int subuvIndex = faceId; + + if (slim) { // select slim arms + subuvIndex += 6; + } + else if (partIdMod == 4) { // select torso + subuvIndex += 12; + } + + vec4 subuv = subuvs[subuvIndex]; + vec2 offset = vec2(0.0); + + #if SPLITMODEL == 1 + // adjust UVs in split cases + if (faceId >= 2) { + subuv.w -= 6.0; + if (partId >= 5) { + subuv.yw += 6.0; + } + } + #endif + + // find the UV offset within the current part + if (faceId == 1) { + if (vertexId == 0) { + offset += subuv.zw; + } + else if (vertexId == 1) { + offset += subuv.xw; + } + else if (vertexId == 2) { + offset += subuv.xy; + } + else { + offset += subuv.zy; + } + } + else { + if (vertexId == 0) { + offset += subuv.zy; + } + else if (vertexId == 1) { + offset += subuv.xy; + } + else if (vertexId == 2) { + offset += subuv.xw; + } + else { + offset += subuv.zw; + } + } + + // apply offset to part origin and normalize + UVout += offset; + UVout2 += offset; + UVout /= float(SKINRES); + UVout2 /= float(SKINRES); + + // assign output + vec3 wpos = Position; + wpos.y += SPACING * (partId + 1); + gl_Position = ProjMat * ModelViewMat * vec4(wpos, 1.0); + + sphericalVertexDistance = fog_spherical_distance(wpos); + cylindricalVertexDistance = fog_cylindrical_distance(wpos); + + texCoord0 = UVout; + texCoord1 = UVout2; + + return; + } + } +#endif +} diff --git a/core/src/main/resources/pack/modelengine_26_2/assets/minecraft/shaders/core/entity.fsh b/core/src/main/resources/pack/modelengine_26_2/assets/minecraft/shaders/core/entity.fsh new file mode 100644 index 0000000..84d2d69 --- /dev/null +++ b/core/src/main/resources/pack/modelengine_26_2/assets/minecraft/shaders/core/entity.fsh @@ -0,0 +1,102 @@ +#version 330 + +#moj_import +#moj_import + +uniform sampler2D Sampler0; + +#if defined(ALPHA_CUTOUT) && !defined(EMISSIVE) && !defined(NO_OVERLAY) && !defined(APPLY_TEXTURE_MATRIX) +#define MAYBE_PLAYERDISP 1 +#endif + +#ifdef DISSOLVE +uniform sampler2D DissolveMaskSampler; +#endif + +in float sphericalVertexDistance; +in float cylindricalVertexDistance; + +#ifdef PER_FACE_LIGHTING +in vec4 vertexPerFaceColorBack; +in vec4 vertexPerFaceColorFront; +#else +in vec4 vertexColor; +#endif + +#ifndef EMISSIVE +in vec4 lightMapColor; +#endif + +#ifndef NO_OVERLAY +in vec4 overlayColor; +#endif + +in vec2 texCoord0; + +out vec4 fragColor; + +#ifdef MAYBE_PLAYERDISP +in vec2 texCoord1; +in float part; + +#define FADERANGE 12.0 +#define FADEBIAS 8.0 +#define MINALPHA 0.25 + +const mat4 bayer4 = mat4( 0.0 / 16.0, 8.0 / 16.0, 2.0 / 16.0, 10.0 / 16.0, +12.0 / 16.0, 4.0 / 16.0, 14.0 / 16.0, 6.0 / 16.0, +3.0 / 16.0, 11.0 / 16.0, 1.0 / 16.0, 9.0 / 16.0, +15.0 / 16.0, 7.0 / 16.0, 13.0 / 16.0, 5.0 / 16.0); + +#endif + +void main() { + vec4 color = texture(Sampler0, texCoord0); +#ifdef ALPHA_CUTOUT + if (color.a < ALPHA_CUTOUT) { + discard; + } +#endif + +#ifdef PER_FACE_LIGHTING + vec4 faceVertexColor = gl_FrontFacing ? vertexPerFaceColorFront : vertexPerFaceColorBack; +#else + vec4 faceVertexColor = vertexColor; +#endif + +#ifdef DISSOLVE + if (faceVertexColor.a < texture(DissolveMaskSampler, texCoord0).a) { + discard; + } + // The dissolve effect entirely replaces translucency + faceVertexColor.a = 1.0; +#endif + + color *= faceVertexColor * ColorModulator; +#ifndef NO_OVERLAY + color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); +#endif +#ifndef EMISSIVE + color *= lightMapColor; +#endif + + fragColor = apply_fog(color, sphericalVertexDistance, cylindricalVertexDistance, FogEnvironmentalStart, FogEnvironmentalEnd, FogRenderDistanceStart, FogRenderDistanceEnd, FogColor); + + #ifdef MAYBE_PLAYERDISP + if (part > 1.0 - 10e-6 && fragColor.a < 1.0) { + fragColor.a = max(fragColor.a, MINALPHA); + + vec3 underCol = texture(Sampler0, texCoord1).rgb; + vec3 trueMix = mix(underCol, fragColor.rgb, fragColor.a); + float fade = mix(fragColor.a, 1.0, clamp((cylindricalVertexDistance - FADEBIAS) / (FADERANGE - FADEBIAS), 0.0, 1.0)); + + fragColor = vec4((trueMix - (1 - fade) * underCol) / fade, fade); + if (fragColor.a < bayer4[int(gl_FragCoord.x) % 4][int(gl_FragCoord.y) % 4] + (0.5 / 16.0)) { + discard; + } + else { + fragColor.a = 1.0; + } + } + #endif +} diff --git a/core/src/main/resources/pack/modelengine_26_2/assets/minecraft/shaders/core/entity.vsh b/core/src/main/resources/pack/modelengine_26_2/assets/minecraft/shaders/core/entity.vsh new file mode 100644 index 0000000..ee0088d --- /dev/null +++ b/core/src/main/resources/pack/modelengine_26_2/assets/minecraft/shaders/core/entity.vsh @@ -0,0 +1,250 @@ +#version 330 + +#if defined(PER_FACE_LIGHTING) || !defined(NO_CARDINAL_LIGHTING) +#moj_import +#endif +#moj_import +#moj_import +#moj_import +#moj_import + +#if defined(ALPHA_CUTOUT) && !defined(EMISSIVE) && !defined(NO_OVERLAY) && !defined(APPLY_TEXTURE_MATRIX) +#define MAYBE_PLAYERDISP 1 +#endif + +#define SPLITMODEL 0 + +in vec3 Position; +in vec4 Color; +in vec2 UV0; +in ivec2 UV1; +in ivec2 UV2; +in vec3 Normal; + +#ifdef MAYBE_PLAYERDISP +uniform sampler2D Sampler0; +#endif + +#ifndef NO_OVERLAY +uniform sampler2D Sampler1; +#endif + +#ifndef EMISSIVE +uniform sampler2D Sampler2; +#endif + +out float sphericalVertexDistance; +out float cylindricalVertexDistance; + +#ifdef PER_FACE_LIGHTING +out vec4 vertexPerFaceColorBack; +out vec4 vertexPerFaceColorFront; +#else +out vec4 vertexColor; +#endif + +#ifndef EMISSIVE +out vec4 lightMapColor; +#endif + +#ifndef NO_OVERLAY +out vec4 overlayColor; +#endif + +out vec2 texCoord0; + +#ifdef MAYBE_PLAYERDISP +out vec2 texCoord1; +out float part; + +#define SPACING 1024.0 +#define MAXRANGE (0.5 * SPACING) +#define SKINRES 64 +#define FACERES 8 + +#define SLIMCHECK0 vec2(54.0 / float(SKINRES), 20.0 / float(SKINRES)) +#define SLIMCHECK1 vec2(55.0 / float(SKINRES), 20.0 / float(SKINRES)) + +const vec4[] subuvs = vec4[]( +vec4(4.0, 0.0, 8.0, 4.0 ), // 4x4x12 +vec4(8.0, 0.0, 12.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 8.0, 16.0), +vec4(8.0, 4.0, 12.0, 16.0), +vec4(12.0, 4.0, 16.0, 16.0), +vec4(4.0, 0.0, 7.0, 4.0 ), // 4x3x12 +vec4(7.0, 0.0, 10.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 7.0, 16.0), +vec4(7.0, 4.0, 11.0, 16.0), +vec4(11.0, 4.0, 14.0, 16.0), +vec4(4.0, 0.0, 12.0, 4.0 ), // 4x8x12 +vec4(12.0, 0.0, 20.0, 4.0 ), +vec4(0.0, 4.0, 4.0, 16.0), +vec4(4.0, 4.0, 12.0, 16.0), +vec4(12.0, 4.0, 16.0, 16.0), +vec4(16.0, 4.0, 24.0, 16.0) +); + +const vec2[] origins = vec2[]( +vec2(40.0, 16.0), // right arm +vec2(40.0, 32.0), +vec2(32.0, 48.0), // left arm +vec2(48.0, 48.0), +vec2(40.0, 16.0), // slim right arm +vec2(40.0, 32.0), +vec2(32.0, 48.0), // slim left arm +vec2(48.0, 48.0), +vec2(16.0, 16.0), // torso +vec2(16.0, 32.0), +vec2(0.0, 16.0), // right leg +vec2(0.0, 32.0), +vec2(16.0, 48.0), // left leg +vec2(0.0, 48.0) +); + +const int[] faceremap = int[](0, 0, 1, 1, 2, 3, 4, 5); +#endif + +void main() { + gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); + + sphericalVertexDistance = fog_spherical_distance(Position); + cylindricalVertexDistance = fog_cylindrical_distance(Position); + +#ifdef PER_FACE_LIGHTING + vec2 light = minecraft_compute_light(Light0_Direction, Light1_Direction, Normal); + vertexPerFaceColorBack = minecraft_mix_light_separate(-light, Color); + vertexPerFaceColorFront = minecraft_mix_light_separate(light, Color); +#elif defined(NO_CARDINAL_LIGHTING) + vertexColor = Color; +#else + vertexColor = minecraft_mix_light(Light0_Direction, Light1_Direction, Normal, Color); +#endif + +#ifndef EMISSIVE + lightMapColor = sample_lightmap(Sampler2, UV2); +#endif + +#ifndef NO_OVERLAY + overlayColor = texelFetch(Sampler1, UV1, 0); +#endif + + texCoord0 = UV0; + +#ifdef APPLY_TEXTURE_MATRIX + texCoord0 = (TextureMat * vec4(UV0, 0.0, 1.0)).xy; +#endif + +#ifdef MAYBE_PLAYERDISP + ivec2 dim = textureSize(Sampler0, 0); + part = 0.0; + texCoord1 = vec2(0.0); + + // check world projmat (not gui), 64x64 texture (player tex dim), valid fog (not hand) + if (abs(ProjMat[2][3]) > 10e-6 && dim.x == SKINRES && dim.y == SKINRES && FogRenderDistanceEnd > FogRenderDistanceStart) { + int partId = -int((Position.y - MAXRANGE) / SPACING); + + part = float(partId); + + if (partId != 0) { + partId -= 1; + // vec4 samp1 = texture(Sampler0, SLIMCHECK0); + // vec4 samp2 = texture(Sampler0, SLIMCHECK1); + bool slim = partId == 2 || partId == 3; //samp1.a == 0.0 || (((samp1.r + samp1.g + samp1.b) == 0.0) && ((samp2.r + samp2.g + samp2.b) == 0.0) && samp1.a == 1.0 && samp2.a == 1.0); + int partIdMod = partId % 7; + int outerLayer = (gl_VertexID / 24) % 2; + int vertexId = gl_VertexID % 4; + int faceId = (gl_VertexID % 24) / 4; + ivec2 faceIdTmp = ivec2(round(UV0 * SKINRES)); + + // find the desired part UV origin + vec2 UVout = origins[2 * partIdMod + outerLayer]; + vec2 UVout2 = origins[2 * partIdMod]; + + // find the player head face UV origin + if ((faceId != 1 && vertexId >= 2) || (faceId == 1 && vertexId <= 1)) { + faceIdTmp.y -= FACERES; + } + if (vertexId == 0 || vertexId == 3) { + faceIdTmp.x -= FACERES; + } + + // calculate a faceId based on face UV origin + faceIdTmp /= FACERES; + faceId = (faceIdTmp.x % 4) + 4 * faceIdTmp.y; + faceId = faceremap[faceId]; + int subuvIndex = faceId; + + if (slim) { // select slim arms + subuvIndex += 6; + } + else if (partIdMod == 4) { // select torso + subuvIndex += 12; + } + + vec4 subuv = subuvs[subuvIndex]; + vec2 offset = vec2(0.0); + + #if SPLITMODEL == 1 + // adjust UVs in split cases + if (faceId >= 2) { + subuv.w -= 6.0; + if (partId >= 5) { + subuv.yw += 6.0; + } + } + #endif + + // find the UV offset within the current part + if (faceId == 1) { + if (vertexId == 0) { + offset += subuv.zw; + } + else if (vertexId == 1) { + offset += subuv.xw; + } + else if (vertexId == 2) { + offset += subuv.xy; + } + else { + offset += subuv.zy; + } + } + else { + if (vertexId == 0) { + offset += subuv.zy; + } + else if (vertexId == 1) { + offset += subuv.xy; + } + else if (vertexId == 2) { + offset += subuv.xw; + } + else { + offset += subuv.zw; + } + } + + // apply offset to part origin and normalize + UVout += offset; + UVout2 += offset; + UVout /= float(SKINRES); + UVout2 /= float(SKINRES); + + // assign output + vec3 wpos = Position; + wpos.y += SPACING * (partId + 1); + gl_Position = ProjMat * ModelViewMat * vec4(wpos, 1.0); + + sphericalVertexDistance = fog_spherical_distance(wpos); + cylindricalVertexDistance = fog_cylindrical_distance(wpos); + + texCoord0 = UVout; + texCoord1 = UVout2; + + return; + } + } +#endif +} diff --git a/core/src/main/resources/pack/pack.mcmeta b/core/src/main/resources/pack/pack.mcmeta new file mode 100644 index 0000000..dcc6577 --- /dev/null +++ b/core/src/main/resources/pack/pack.mcmeta @@ -0,0 +1,82 @@ +{ + "pack": { + "pack_format": 15, + "min_format": 15, + "max_format": 32767, + "supported_formats": [15, 32767], + "description": "Pre-zipped Model Engine Resource Pack" + }, + "overlays": { + "entries": [ + { + "min_format": 15, + "max_format": 36, + "formats": { + "min_inclusive": 15, + "max_inclusive": 36 + }, + "directory": "modelengine_1_19_4" + }, + { + "min_format": 36, + "max_format": 54, + "formats": { + "min_inclusive": 36, + "max_inclusive": 54 + }, + "directory": "modelengine_1_21_2" + }, + { + "min_format": 46, + "max_format": 62, + "formats": { + "min_inclusive": 46, + "max_inclusive": 62 + }, + "directory": "modelengine_1_21_4" + }, + { + "min_format": 55, + "max_format": 62, + "formats": { + "min_inclusive": 55, + "max_inclusive": 62 + }, + "directory": "modelengine_1_21_5" + }, + { + "min_format": 63, + "max_format": 83, + "formats": { + "min_inclusive": 63, + "max_inclusive": 83 + }, + "directory": "modelengine_1_21_6" + }, + { + "min_format": 84, + "max_format": 87, + "formats": { + "min_inclusive": 84, + "max_inclusive": 87 + }, + "directory": "modelengine_26_1" + }, + { + "min_format": 88, + "max_format": 96, + "formats": { + "min_inclusive": 88, + "max_inclusive": 96 + }, + "directory": "modelengine_26_2" + } + ] + }, + "sodium": { + "ignored_shaders": [ + "rendertype_entity_translucent.fsh", + "rendertype_entity_translucent.vsh" + ] + } +} diff --git a/core/src/main/resources/pack/pack.png b/core/src/main/resources/pack/pack.png new file mode 100644 index 0000000000000000000000000000000000000000..062e04b6cb8bd7e19f5044a6f9da9ccf2e513f41 GIT binary patch literal 6586 zcmV;r8AaxaP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGqBme*wBmtWh#uNYm8Ba+>K~#8N#ajtr zRMpk~X30!4*%Js^$O43278R`<0t&L~FDQyq1Pf@@x+C?kOI6frEs6@YKZsT>D78{r zC@Me5A|Mc!BnA-3LP!GHmzgZH&;Ok}GhrqPn=JnaCvV<;_uYHWch5cd+&6DD_Icb1;8fCQg`;ZC%mVZ4wsYw8Xm^O49c^VG${)}G39m2rzFCvN-hB|838nY z6c4XZu2BW2#&*h!Bw>U1^y1>86F|dz^Y9{NG9^UH+#de1X^;}>L8#7y0yEXn@jpc_ z5e~`<$~+QrSe0BPTr>h`cpMLpQXZqoXJwqHMT5KgJ1~1xE&3+c(QX$?s-m%CYbVU# zWmFVtPij>|d6%+~MAWI03ycd+01emka2MqTN*^hcPFyzN$^;MQ-d2y%gN`CvTM5{; za+x=|VRJ=d$Dtm0Z(S#>JgSGr;0aXjAmwGsS0uuzN-hvCC;>EH=C{mqneSf1MO{)d ze|!_}9#)E!=%YXj%iI*@5_7hySKXgqKL~o#%|@j}NzF=Gb!d?_3D2(}n{zy|L$~Sh_wdNF5=9;&uT&yENe! znfujwNo6{|*p`a9J58#dj?UsEqM7m$mwvhnVB@1px2=*6s#~;2; z!RKZAz}O%tqr6Fx{6R?hS&*L288lp@Nz5G2kDpNPr$kD*AEKw;qrt!w4>G#gVG6av ztcgQuLo&7>h{ZQ0A<%}h9s{0VJe0m{B`wYfokjied{b#ZQt$grb{OXY$*t_+L=ZAQN>IDzmL*L0v$7?WWN)bl%*P*sF6i4bcL9QyFHNMqO z;C8s+sc(VDYw~aO~4-?NH&9q^`=n~AlsucZ0LXlTt zM2%D9Cth@u{l!G;+(0?VX(8TmO0?-B7&KlQlVxp~oJ(a{&%4C}&rh@9w(E|elZ~;c zmRFM8*jYLN*F2ltZnV{Xb|)gk445`{C6iKVMdQaOU zxVjHCJcS1_d@6;GO$CHUuIVq`W5u-b$I(5B>v&@7@X$zJtT8yR^oAL%fM2GjU zYQ(Q^+6|4KmDz@t9_4D%Bl}n;{*sl5r4_5QiWMlOiGY=*z?#={+Ot%xSN;V%W9C2)9(xKmB}3kn+GJQQt2e z7%%A6H35dmXt=0&4Y~V~Y49<&dz_L_=ggxxe53D&oEk&)h>GJLO0A72A;t(FiW6$D z$PBzcQj3IClF+>b*F2^+RyyhQ3%*ZD3O6z2rj#MI5meL6^ynWLLSAbX7p8 z7$Cxt`|Vve+<)5%^ol5gGt`Kmic`7S(QqzmP*G#V^aY(z(}r|6m$^ApZpHLzcf%eP zD>|y{!Frv9*i&3lgOy)=iH%>cgSoM(H4uvN*O=V+(})U$g)sP$z)-Cdmu2LWNCS4~ zWn$631T3qOK*(PBzs;&pL>b69z(w4PAbL6f#XTOP#K^fQI;N)^`Q>bdSGFC{+@v7Y7B1AM-!%dIaRooksUr$o=+Yh~7hqSa*COx5W(HnYqiAV2l zsYvL;*kCfjL0uaf8&Ohrf`$~Mvbt6!L{_U6)m7EZ5xkB0M}O&rV)V<*=g_%PS(1!Z zd(-h!UL;OPGDO?mOtPljGzbsQzK`zY!icGJp^a4=R6#orI6VOkJo%~u17dT~piRcN zS!sB4NhJ0b@-~SSjT%fJ>cI5zwb*ws0&~7HNlFmpc3NuHxpO>1Nr1s%KnR1IXxcjW z8kDt zc>IB>7&2@)oRN{J%FV%uNsmGs&m_r)t1>t; ziJI7q(E}YrsNXI>+;(0wku8$}T}(`UNq~+T3o+uFk`lYQ-io14r;};11JzbGED_ep zfI@@YMrxImaknYgBnlcBDCfM~g*1H^SI#!EjRpUhQ3jZ~vyZHjT{M*0g%gsqiFnN zWw<<*yHn=uGB2D6!?G<`V8&N52n~}2g&rXP=-W2C8*g1}!6PGc5o%~;s!Qg{Z%Iiy zo>`rV73C)%h`7yGjK8K2X3hE~dR=)Hn)F84+K?oxXG2~#Zn@*J^YZ|YWH4$i41o01 zqD6?!0Ye7~kX+u++~C7C35*y0;L$RBu+yZF1{Q7W?L6FsQ{z3vgB*59001i@I7}g%_i#NWA#g3yI=olCM zI*DCsA0~ZsUiOLh;CExqm~iD$#2U+4CWc8RKRmEDMPbYS9(ZR{Jie)*Ysrq!Y{PxG zUWa?8-Gh|A{m{gyD=SEl;y%a}F_GDt!XsGu`QNc<)h5QKAQwGH0-8v`d&eL0!=nypUFbYk*IGu~etgAIqdGb1@}?i?p{bK;57HMqWKAzhx! z42^L)jL0kQj>Q`j@#lk#rlKVD_x3=ymnAup7fVbag+%IOlCu71+4uKbXIK z4Qjay?HsB@O|y(bE6$MsCOkRwNq~U_xKBZVfDySeGzBx>>Wj?IPQ3qv5f5Hr$HIqq zq0SkDReRDf?;nvUp}i^-=aheFpdBOoGx9T`$tnoP%e#H;dQtE>+FGLrD?yKhCbDHPKmo5xkE_2J4n62P@T z=M54NMglyiA%L1!hNR%7PkQ2wnFp}1G!a{}qVVj5Y=lIyug*H;S9QZD|4PQItBfjN zP@6o-5yU9@7Kny;>`pv4bsX-xdlI^4WXQ}>;X&rQ#A11H(m;{WA`gTN%oB=!%)#={ zR$%3x!w8R$!NX&3#Mtqp5ue%>ML9XReKPZaxSzWU2t950s;7Wn>q0o!eIs3NSV}gY zzHdKt={6vmU2y0!N}k%ygH*4KtnXneFG1fRV90v>$wF{IFV>DF(& zh^P|9dWj@2mPhl^LVUd7J={6xHLN^bhI>a{htFP}iz&aFfv}{mXcnT{u3jDB%mm0V zbQErbph29c639+~^$ZnWXuXCK7X z!-nCQORx44e%=)Ua->L*YvI;<-RH|O>+$EYa6=Y`4(N@=zkLW#%pr08`ZHb8DQ^+@ z4yVN#3Gi_4omETJG(NfWulfn_iPmnz#9_zLGv3>%{Jm~K25z`dP$yL%5Fc>Fm$_3iFGb)Wc9Wc5p1io;;Biau$1mT@y^@f4v)g&dJF2fc@mPu?QOoNNZ!Av z$C;;q_+m#)%AMh?5J!<9D|I?DSj1n>WffH(=()BhM6y8DW%d_tB5xX0lYmmrATcK}BkWp@;W@5aIz8_+xWO))VWcv85mV@tO5Tr~D7H^QiXri`p)I|s> zVy0KrWao0{R$ktCybRwhTaJ%D{1ins4H!Fa6edrf0ylGu)8X_4_!Z{XRgs`5KPiqT zEe@;;hpUDcrA!Er2PYQZD9c=+Rnk)|C53H8s*+Z8VJ3R%_~*uJ=atgM4X^~-yaJZLZ+`ViOx?mrdIJO#vsMcF`6qVJP$z!M+mB@nKfsD*|A3SAhg>rRH&2_2uGbHRB{Uq(@_ixOb4bI!K2C)* zdVog=@EhzWKtzmZV6$U=o9LzzIQ@o823|>}WJL%F ziqf3Ve&jK_=bD?jPCmXuP?)7xwOmK&U+O zk(eNBf143k_evW+NJtS#$NtZLNVT#?D~g%i7>q__ju?)?zq}6_SN}qN+pJOZhf{~6 zU1xXk$W?*odaahLRGY>+KwAQ2d?a7~Lu1A!-G$1U--NL2eN7wIwz*b1vuBSeVc-!1*poAly+=k4=>gG|q{nE3Zbs zTgD(RKAww`>NN;bBFkkBbAJP@2nky()H=yce=$3WNtGr@P7^FoeUbzy%5wojSPfTQR?}O41!b*@PGyeww*LG zhk;I9S0I;nkdPvdyg<*zzH?kOlOgG_z3~DY-KV6a6kC^liq)^ahN9d9)Gx@y?`UIS zX42slkazFo)l}7uBpDJ~=5TJ``a@5wSTzI;4D0dM>goqrs22+m5V%9g8Vatkvuw^mw8zQm4r7Qkg zo`9{^0C$s{0!FzV0XHw) zLs@66DUZd6HKAMqTi?V`ieJeDVO-zi&?N;;IWM?+Z2mD7o2xmGn7?=L+Y5cKxLgHP z=_Qu@8V z+uIY|=Gy53E?%hNzJDiocwceDv;M6=!BTjX?jE$R3$iJbD0fgdc@^%Q&|wff6BtlD zl%E(Rm-AF!I~hokJ)eTuTFAfus*6EHUT36nFB=}s7$grXRrK{-WU+Wrj<&lR0i={e$O5#R?q zwNbW_2zgUm2Ow#}c(hE?dnnISB!_5)f7-v|Y{3z|9-lFvmO!b`>TaMc)6H$1WEf7mWZvNQC^tV_(3A%4GQ_y_*_csugrXqjf(6@Na;KEIfTpZD(o&kex;0mjko$9FEdTL1t607*qoM6N<$f&(gHEC2ui literal 0 HcmV?d00001 diff --git a/core/src/main/resources/plugin.yml b/core/src/main/resources/plugin.yml new file mode 100644 index 0000000..5a8fe1f --- /dev/null +++ b/core/src/main/resources/plugin.yml @@ -0,0 +1,25 @@ +name: ModelEngine +version: R4.2.0 +main: com.ticxo.modelengine.core.ModelEngine +load: STARTUP +authors: + - Ticxo +libraries: + - net.kyori:adventure-api:4.14.0 + - net.kyori:adventure-text-serializer-gson:4.14.0 + - net.kyori:adventure-text-serializer-bungeecord:4.3.0 +commands: + meg: + description: All things Model Engine related. + permission-message: You do not have permission to use this command. +permissions: + modelengine.command: + description: Access to all Model Engine commands. + default: op +api-version: "1.19" +softdepend: + - MythicMobs + - Citizens + - LibsDisguises + - ViaVersion +folia-supported: true diff --git a/core21/build.gradle.kts b/core21/build.gradle.kts new file mode 100644 index 0000000..8bfb200 --- /dev/null +++ b/core21/build.gradle.kts @@ -0,0 +1,8 @@ +dependencies { + compileOnly(project(":api")) + compileOnly(project(":core")) + listOf("v1_20_R4", "v1_21_R1", "v1_21_R2", "v1_21_R3", "v1_21_R4", "v1_21_R5", "v1_21_R6", "v1_21_R7") + .forEach { compileOnly(project(":nms:$it")) } + compileOnly("io.papermc.paper:paper-api:1.21.11-R0.1-SNAPSHOT") + compileOnly("io.lumine:Mythic-Dist:5.14.0") { isTransitive = false } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/Java21Helper.java b/core21/src/main/java/com/ticxo/modelengine/core21/Java21Helper.java new file mode 100644 index 0000000..66c44c9 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/Java21Helper.java @@ -0,0 +1,47 @@ +package com.ticxo.modelengine.core21; + +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.utils.CompatibilityManager; +import com.ticxo.modelengine.core.ModelEngine; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.compatibility.MythicCompatibility; +import com.ticxo.modelengine.v1_20_R4.NMSHandler_v1_20_R4; +import com.ticxo.modelengine.v1_21_R1.NMSHandler_v1_21_R1; +import com.ticxo.modelengine.v1_21_R2.NMSHandler_v1_21_R2; +import com.ticxo.modelengine.v1_21_R3.NMSHandler_v1_21_R3; +import com.ticxo.modelengine.v1_21_R4.NMSHandler_v1_21_R4; +import com.ticxo.modelengine.v1_21_R5.NMSHandler_v1_21_R5; +import com.ticxo.modelengine.v1_21_R6.NMSHandler_v1_21_R6; +import com.ticxo.modelengine.v1_21_R7.NMSHandler_v1_21_R7; +import java.io.File; +import java.util.List; + +public class Java21Helper { + private static MythicCompatibility mythicCompatibility; + + public static void registerCompatibility(CompatibilityManager compatibilityManager, ModelEngine plugin) { + compatibilityManager.registerSupport("MythicMobs", () -> mythicCompatibility = new MythicCompatibility(plugin)); + } + + public static NMSHandler createNMSHandler(String version) { + return (NMSHandler)(switch (version) { + case "1.20.5", "1.20.6" -> new NMSHandler_v1_20_R4(); + case "1.21", "1.21.1" -> new NMSHandler_v1_21_R1(); + case "1.21.2", "1.21.3" -> new NMSHandler_v1_21_R2(); + case "1.21.4" -> new NMSHandler_v1_21_R3(); + case "1.21.5" -> new NMSHandler_v1_21_R4(); + case "1.21.6", "1.21.7", "1.21.8" -> new NMSHandler_v1_21_R5(); + case "1.21.9", "1.21.10" -> new NMSHandler_v1_21_R6(); + case "1.21.11" -> new NMSHandler_v1_21_R7(); + default -> null; + }); + } + + public static List getMythicPackModelFiles() { + return MythicUtils.getPackModelFiles(); + } + + public static MythicCompatibility getMythicCompatibility() { + return mythicCompatibility; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/MythicUtils.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/MythicUtils.java new file mode 100644 index 0000000..92f1c87 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/MythicUtils.java @@ -0,0 +1,216 @@ +package com.ticxo.modelengine.core21.mythic; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.mount.controller.MountControllerSupplier; +import com.ticxo.modelengine.core21.Java21Helper; +import com.ticxo.modelengine.core21.mythic.compatibility.MythicMountController; +import com.ticxo.modelengine.core21.mythic.compatibility.ProjectileEntity; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.packs.Pack; +import io.lumine.mythic.api.skills.IParentSkill; +import io.lumine.mythic.api.skills.Skill; +import io.lumine.mythic.api.skills.SkillCaster; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.bukkit.MythicBukkit; +import io.lumine.mythic.core.skills.auras.AuraAttachment.AttachmentTracker; +import io.lumine.mythic.core.skills.auras.attachment.MEGAttachment.MEGAttachmentTracker; +import io.lumine.mythic.core.skills.placeholders.PlaceholderMeta; +import io.lumine.mythic.core.skills.projectiles.ProjectileBulletableTracker; +import io.lumine.mythic.core.skills.projectiles.ProjectileBullet.BulletTracker; +import io.lumine.mythic.core.skills.projectiles.bullet.MEGBullet.MEGBulletTracker; +import java.io.File; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; +import org.bukkit.Color; +import org.jetbrains.annotations.Nullable; + +public class MythicUtils { + public static String getOrNull(@Nullable PlaceholderString placeholderString) { + return placeholderString == null ? null : placeholderString.get(); + } + + public static String getOrNull(@Nullable PlaceholderString placeholderString, PlaceholderMeta meta) { + return placeholderString == null ? null : placeholderString.get(meta); + } + + public static String getOrNull(@Nullable PlaceholderString placeholderString, AbstractEntity entity) { + return placeholderString == null ? null : placeholderString.get(entity); + } + + public static String getOrNull(@Nullable PlaceholderString placeholderString, PlaceholderMeta meta, AbstractEntity entity) { + return placeholderString == null ? null : placeholderString.get(meta, entity); + } + + public static String getOrNull(@Nullable PlaceholderString placeholderString, SkillCaster caster) { + return placeholderString == null ? null : placeholderString.get(caster); + } + + public static String getOrNullLowercase(@Nullable PlaceholderString placeholderString) { + return placeholderString == null ? null : placeholderString.get().toLowerCase(Locale.ENGLISH); + } + + public static String getOrNullLowercase(@Nullable PlaceholderString placeholderString, PlaceholderMeta meta) { + return placeholderString == null ? null : placeholderString.get(meta).toLowerCase(Locale.ENGLISH); + } + + public static String getOrNullLowercase(@Nullable PlaceholderString placeholderString, AbstractEntity entity) { + return placeholderString == null ? null : placeholderString.get(entity).toLowerCase(Locale.ENGLISH); + } + + public static String getOrNullLowercase(@Nullable PlaceholderString placeholderString, PlaceholderMeta meta, AbstractEntity entity) { + return placeholderString == null ? null : placeholderString.get(meta, entity).toLowerCase(Locale.ENGLISH); + } + + public static String getOrNullLowercase(@Nullable PlaceholderString placeholderString, SkillCaster caster) { + return placeholderString == null ? null : placeholderString.get(caster).toLowerCase(Locale.ENGLISH); + } + + public static Color getColor(@Nullable String colorString) { + if (colorString == null) { + return Color.WHITE; + } else { + if (colorString.startsWith("#")) { + colorString = colorString.substring(1); + } + + return Color.fromRGB(Integer.parseInt(colorString, 16)); + } + } + + public static ActiveModel getActiveModelOrNull(ModeledEntity entity, @Nullable String modelId) { + return modelId == null ? null : entity.getModel(modelId.toLowerCase(Locale.ENGLISH)).orElse(null); + } + + public static ModelBlueprint getBlueprintOrNull(@Nullable String modelid) { + return modelid == null ? null : ModelEngineAPI.getBlueprint(modelid); + } + + public static ProjectileEntity getProjectileEntity(SkillMetadata meta) { + return castProjectileEntity(meta).map(tracker -> Java21Helper.getMythicCompatibility().getMythicSupport().getTrackers().get(tracker)).orElse(null); + } + + public static Optional castProjectileEntity(SkillMetadata metadata) { + return metadata.getCallingEvent() instanceof ProjectileBulletableTracker tracker ? castProjectileEntity(tracker) : Optional.empty(); + } + + public static Optional castProjectileEntity(ProjectileBulletableTracker tracker) { + return tracker instanceof IParentSkill ? Optional.of((T)tracker) : Optional.empty(); + } + + public static UUID getVFXUniqueId(SkillMetadata meta) { + ProjectileEntity base = getProjectileEntity(meta); + return base != null ? base.getUUID() : meta.getCaster().getEntity().getUniqueId(); + } + + public static void executeOptModelId(ModeledEntity entity, String modelId, Consumer consumer) { + if (modelId == null) { + for (ActiveModel activeModel : entity.getModels().values()) { + consumer.accept(activeModel); + } + } else { + ActiveModel activeModel = getActiveModelOrNull(entity, modelId); + if (activeModel != null) { + consumer.accept(activeModel); + } + } + } + + public static void executeBoneChild(boolean child, ModelBone bone, Consumer boneConsumer) { + boneConsumer.accept(bone); + if (child) { + LinkedList queue = new LinkedList<>(bone.getChildren().values()); + + while (!queue.isEmpty()) { + ModelBone childBone = queue.pop(); + boneConsumer.accept(childBone); + queue.addAll(childBone.getChildren().values()); + } + } + } + + public static MountControllerSupplier createControllerSupplier(Skill skill, SkillMetadata metadata) { + return (entity, mount) -> new MythicMountController(entity, mount, skill, metadata); + } + + public static List getPackModelFiles() { + List files = Lists.newArrayList(); + + for (Pack pack : MythicBukkit.inst().getPackManager().getPacks()) { + File folder = pack.getPackFolder("Models"); + if (folder.exists()) { + addFilesRecursively(folder, files); + } + + folder = new File(pack.getPackFolder("Assets"), "modelengine"); + if (folder.exists()) { + addFilesRecursively(folder, files); + } + } + + return files; + } + + private static void addFilesRecursively(File folder, List files) { + File[] fileList = folder.listFiles(); + if (fileList != null) { + for (File file : fileList) { + if (file.isFile() && file.getName().endsWith(".bbmodel")) { + files.add(file); + } else if (file.isDirectory()) { + addFilesRecursively(file, files); + } + } + } + } + + public static Optional findSkillableModel(SkillMetadata data, UUID target) { + if (target != null) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target); + if (model != null) { + return Optional.of(model); + } + } + + return getParentVFXModel(data); + } + + public static Optional getParentVFXModel(SkillMetadata meta) { + Optional maybeBullet = meta.getMetadata("bullet"); + if (maybeBullet.isPresent()) { + return getParentVFXModel((BulletTracker)maybeBullet.get()); + } else { + Optional maybeAttachment = meta.getMetadata("attachment"); + return maybeAttachment.isPresent() ? getParentVFXModel((AttachmentTracker)maybeAttachment.get()) : Optional.empty(); + } + } + + private static Optional getParentVFXModel(BulletTracker bulletTracker) { + if (bulletTracker instanceof MEGBulletTracker megBulletTracker) { + UUID entityId = megBulletTracker.getEntityId(); + ModeledEntity model = ModelEngineAPI.getModeledEntity(entityId); + return Optional.ofNullable(model); + } else { + return Optional.empty(); + } + } + + private static Optional getParentVFXModel(AttachmentTracker bulletTracker) { + if (bulletTracker instanceof MEGAttachmentTracker megBulletTracker) { + UUID entityId = megBulletTracker.getEntityId(); + ModeledEntity model = ModelEngineAPI.getModeledEntity(entityId); + return Optional.ofNullable(model); + } else { + return Optional.empty(); + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/animation/MythicScriptReader.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/animation/MythicScriptReader.java new file mode 100644 index 0000000..4ff88cd --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/animation/MythicScriptReader.java @@ -0,0 +1,50 @@ +package com.ticxo.modelengine.core21.mythic.animation; + +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.animation.script.ScriptReader; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import io.lumine.mythic.bukkit.MythicBukkit; +import io.lumine.mythic.core.mobs.ActiveMob; +import org.bukkit.entity.Entity; + +public class MythicScriptReader implements ScriptReader { + @Override + public void read(IAnimationProperty property, String script) { + ActiveModel model = property.getModel(); + ModelBlueprint blueprint = model.getBlueprint(); + if (model.getModeledEntity().getBase().getOriginal() instanceof Entity entity) { + float power = 1.0F; + ActiveMob activeMob = MythicBukkit.inst().getAPIHelper().getMythicMobInstance(entity); + if (activeMob != null) { + power = activeMob.getPower(); + } + + String[] scriptSplit = script.split("\\{", 2); + String skillName = scriptSplit[0]; + boolean succeed = MythicBukkit.inst().getAPIHelper().castSkill(entity, skillName, power, meta -> { + if (scriptSplit.length == 2) { + String[] parameters = scriptSplit[1].substring(0, scriptSplit[1].length() - 1).split(";"); + + for (String param : parameters) { + String[] entry = param.split("=", 2); + meta.getParameters().put(entry[0], entry.length == 2 ? this.getAnimationPlaceholder(blueprint, entry[1].strip()) : ""); + } + } + }); + if (!succeed) { + TLogger.warn("Unknown MythicMobs script: " + script); + } + } + } + + private String getAnimationPlaceholder(ModelBlueprint blueprint, String placeholder) { + if (placeholder.startsWith("<") && placeholder.endsWith(">")) { + String key = placeholder.substring(1, placeholder.length() - 1); + return blueprint.getAnimationsPlaceholders().getOrDefault(key, placeholder); + } else { + return placeholder; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/AuraAttachment.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/AuraAttachment.java new file mode 100644 index 0000000..610a4ca --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/AuraAttachment.java @@ -0,0 +1,144 @@ +package com.ticxo.modelengine.core21.mythic.compatibility; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.BlueprintAnimation; +import com.ticxo.modelengine.api.animation.handler.AnimationHandler; +import com.ticxo.modelengine.api.animation.handler.IStateMachineHandler; +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.animation.property.SimpleProperty; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.Segment; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.bukkit.BukkitAdapter; +import io.lumine.mythic.bukkit.compatibility.AbstractModelEngineSupport.MEGAttachment; +import io.lumine.mythic.bukkit.compatibility.AbstractModelEngineSupport.MEGAttachmentData; +import io.lumine.mythic.core.logging.MythicLogger; +import java.util.UUID; +import java.util.Map.Entry; +import org.bukkit.Color; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +public class AuraAttachment implements MEGAttachment { + private Entity entity; + private FakeEntity attachedEntity; + private ModelBlueprint modelBlueprint; + private ActiveModel activeModel; + private ModeledEntity modeledEntity; + + public AuraAttachment(MEGAttachmentData modelData, AbstractEntity target) { + this.entity = BukkitAdapter.adapt(target); + String modelId = modelData.getModelId(); + String state = modelData.getState(); + double scale = modelData.getScale(); + String color = modelData.getColor(); + boolean enchanted = modelData.isEnchanted(); + boolean glowing = modelData.isGlowing(); + String glowColor = modelData.getGlowColor(); + Integer brightness = modelData.getBrightness(); + this.modelBlueprint = ModelEngineAPI.getBlueprint(modelId); + if (this.modelBlueprint == null) { + MythicLogger.error("Failed to spawn Aura Attachment: Model " + modelId + " not found"); + } else { + this.activeModel = ModelEngineAPI.createActiveModel(this.modelBlueprint); + this.activeModel.setCanHurt(false); + this.activeModel.setScale(scale); + this.activeModel.setHitboxScale(0.0); + if (color != null) { + if (color.startsWith("#")) { + color = color.substring(1); + } + + this.activeModel.setDefaultTint(Color.fromRGB(Integer.parseInt(color, 16))); + } + + if (brightness != null) { + this.activeModel.setBlockLight(brightness); + this.activeModel.setSkyLight(brightness); + } + + for (Entry entry : this.activeModel.getBones().entrySet()) { + ModelBone bone = entry.getValue(); + if (enchanted) { + bone.setEnchanted(true); + } + + bone.getBoneBehavior(BoneBehaviorTypes.SEGMENT).ifPresent(segment -> ((Segment)segment).setBounded(false)); + } + + if (state != null) { + AnimationHandler handler = this.activeModel.getAnimationHandler(); + if (handler instanceof IStateMachineHandler stateMachineHandler) { + IAnimationProperty property = stateMachineHandler.playAnimation(100, state, 0.0, 0.0, 1.0, true); + if (property != null) { + property.setForceLoopMode(BlueprintAnimation.LoopMode.LOOP); + } + } else { + IAnimationProperty property = handler.playAnimation(state, 0.0, 0.0, 1.0, true); + if (property != null) { + property.setForceLoopMode(BlueprintAnimation.LoopMode.LOOP); + } + } + } + + this.attachedEntity = new FakeEntity(this.entity, modelData.getOffset(), modelData.getAnchor()); + this.attachedEntity.setCollidableWith(this.entity, false); + this.modeledEntity = ModelEngineAPI.createModeledEntity(this.attachedEntity); + this.modeledEntity.getAnimationLodHandler().setEnabled(modelData.isUseALOD()); + this.modeledEntity.getBase().getBodyRotationController().setPlayerMode(true); + this.modeledEntity.setBaseEntityVisible(true); + this.modeledEntity.addModel(this.activeModel, false); + this.activeModel.setPivotOverride(ModelEngineAPI.getPivotOverrideRegistry().getOrCreate(this.entity)); + if (glowing) { + this.activeModel.setGlowing(true); + if (glowColor != null) { + if (glowColor.startsWith("#")) { + glowColor = glowColor.substring(1); + } + + this.activeModel.setGlowColor(Integer.parseInt(glowColor, 16)); + } + } + + if (this.entity instanceof Player player && this.modeledEntity.getBase().getData() instanceof BukkitEntityData data) { + data.getTracked().addForcedPairing(player.getUniqueId()); + } + } + } + + public UUID getEntityId() { + return this.attachedEntity.getUUID(); + } + + public void setRenderRadius(int radius) { + BukkitEntityData data = this.attachedEntity.getData(); + } + + public void disableCulling() { + BukkitEntityData data = this.attachedEntity.getData(); + data.setVerticalCull(false); + data.setBackCull(false); + data.setBlockedCull(false); + data.cullUpdate(); + } + + public void close() throws Exception { + BlueprintAnimation animation = this.modelBlueprint.getAnimations().get("death"); + if (animation == null) { + ModelEngineAPI.removeModeledEntity(this.attachedEntity.getUUID()); + } else { + SimpleProperty property = new SimpleProperty(this.activeModel, animation, 1.0, 0.0, 1.0); + property.setForceLoopMode(BlueprintAnimation.LoopMode.ONCE); + property.setForceOverride(BlueprintAnimation.OverrideMode.OVERRIDE); + property.setOnEndTask(() -> ModelEngineAPI.removeModeledEntity(this.attachedEntity.getUUID())); + if (!this.activeModel.getAnimationHandler().playAnimation(property, true)) { + ModelEngineAPI.removeModeledEntity(this.attachedEntity.getUUID()); + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/FakeEntity.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/FakeEntity.java new file mode 100644 index 0000000..3d615c7 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/FakeEntity.java @@ -0,0 +1,68 @@ +package com.ticxo.modelengine.core21.mythic.compatibility; + +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import io.lumine.mythic.bukkit.compatibility.AbstractModelEngineSupport.MEGAttachmentAnchor; +import io.lumine.mythic.bukkit.utils.serialize.Orient; +import java.util.UUID; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; + +public class FakeEntity extends BukkitEntity { + private final UUID uuid = UUID.randomUUID(); + private final Vector offset; + private final double yaw; + private final double pitch; + private final MEGAttachmentAnchor anchor; + + public FakeEntity(@NotNull Entity entity, Orient orient, MEGAttachmentAnchor anchor) { + super(entity); + this.offset = orient.getLocus().toVector(); + this.yaw = Math.toRadians(orient.getDirection().getYaw()); + this.pitch = Math.toRadians(orient.getDirection().getPitch()); + this.anchor = anchor; + this.getBodyRotationController().setMaxHeadAngle(45.0F); + this.getBodyRotationController().setMaxBodyAngle(45.0F); + this.getBodyRotationController().setStableAngle(5.0F); + } + + @Override + public UUID getUUID() { + return this.uuid; + } + + @Override + public Location getLocation() { + BodyRotationController controller = this.getBodyRotationController(); + Location location = this.getOriginal().getLocation(); + Vector offset; + if (this.anchor == MEGAttachmentAnchor.HEAD) { + double pYaw = Math.toRadians(location.getYaw()); + double pPitch = Math.toRadians(location.getPitch()); + offset = rotateYaw(rotatePitch(this.offset.clone(), this.pitch + pPitch), this.yaw + pYaw); + } else { + double pYaw = Math.toRadians(controller == null ? this.getYBodyRot() : controller.getYBodyRot()); + offset = rotateYaw(this.offset.clone(), this.yaw + pYaw); + } + + return location.add(offset); + } + + public static Vector rotatePitch(Vector vec, double pitch) { + double sin = Math.sin(pitch); + double cos = Math.cos(pitch); + double y = vec.getY() * cos - vec.getZ() * sin; + double z = vec.getY() * sin + vec.getZ() * cos; + return vec.setY(y).setZ(z); + } + + public static Vector rotateYaw(Vector vec, double yaw) { + double sin = Math.sin(yaw); + double cos = Math.cos(yaw); + double x = vec.getX() * cos - vec.getZ() * sin; + double z = vec.getX() * sin + vec.getZ() * cos; + return vec.setX(x).setZ(z); + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MEGModel.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MEGModel.java new file mode 100644 index 0000000..1595a1c --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MEGModel.java @@ -0,0 +1,108 @@ +package com.ticxo.modelengine.core21.mythic.compatibility; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.NameTag; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicConfig; +import io.lumine.mythic.api.mobs.MythicMob; +import io.lumine.mythic.bukkit.BukkitAdapter; +import io.lumine.mythic.core.logging.MythicLogger; +import io.lumine.mythic.core.mobs.model.MobModel; +import java.util.Locale; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.bukkit.entity.Entity; + +public class MEGModel extends MobModel { + private final String id; + private String nameplate = ""; + private double stepHeight = 0.5; + private int viewRadius = 0; + private double scale = 1.0; + private double hitboxScale = 1.0; + private boolean useHitbox = true; + private boolean invisible = true; + private boolean doDamageTint = true; + private boolean canDrive = false; + private boolean canRide = false; + private boolean lockPitch = false; + private boolean lockYaw = false; + + public MEGModel(MythicMob baseMob, MythicConfig config) { + super(baseMob, config); + if (config.isConfigurationSection("Model")) { + String tempId = config.getString("Model.Id", null); + this.id = tempId == null ? null : tempId.toLowerCase(Locale.ENGLISH); + this.nameplate = config.getString("Model.Nameplate", null); + this.stepHeight = config.getDouble("Model.Step", 0.5); + this.viewRadius = config.getInteger("Model.ViewRadius", 0); + this.useHitbox = config.getBoolean("Model.Hitbox", true); + this.invisible = config.getBoolean("Model.Invisible", true); + this.doDamageTint = config.getBoolean("Model.DamageTint", true); + this.canDrive = config.getBoolean("Model.Drive", false); + this.canRide = config.getBoolean("Model.Ride", false); + this.lockPitch = config.getBoolean("Model.LockPitch", false); + this.lockYaw = config.getBoolean("Model.LockYaw", false); + this.scale = config.getDouble("Model.Scale", 1.0); + this.hitboxScale = config.getDouble("Model.HitboxScale", this.scale); + } else { + this.id = config.getString("Model"); + } + } + + public void apply(AbstractEntity entity) { + if (this.id == null) { + MythicLogger.error("ModelEngine ID not specified"); + } else { + ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(this.id); + if (blueprint == null) { + MythicLogger.error("Unable to find model with ID {0}", new Object[]{this.id}); + } else { + Entity bukkitTarget = BukkitAdapter.adapt(entity); + ModeledEntity model = ModelEngineAPI.getOrCreateModeledEntity(bukkitTarget.getUniqueId(), () -> { + BukkitEntity baseEntity = new BukkitEntity(bukkitTarget); + baseEntity.setMaxStepHeight(this.stepHeight); + if (this.viewRadius > 0) { + baseEntity.setRenderRadius(this.viewRadius); + } + + return baseEntity; + }); + if (model.getModel(this.id).isPresent()) { + MythicLogger.error("Entity already contains model with ID {0}", new Object[]{this.id}); + } else { + model.setBaseEntityVisible(!this.invisible); + ActiveModel activeModel = ModelEngineAPI.createActiveModel(blueprint); + activeModel.setScale(this.scale); + activeModel.setHitboxScale(this.hitboxScale); + activeModel.getMountManager().ifPresent(mountManager -> { + ((MountManager)mountManager).setCanDrive(this.canDrive); + ((MountManager)mountManager).setCanRide(this.canRide); + }); + activeModel.setCanHurt(this.doDamageTint); + activeModel.setLockPitch(this.lockPitch); + activeModel.setLockYaw(this.lockYaw); + model.addModel(activeModel, this.useHitbox).ifPresent(ActiveModel::destroy); + activeModel.getBone(this.nameplate) + .flatMap(modelBone -> modelBone.getBoneBehavior(BoneBehaviorTypes.NAMETAG)) + .ifPresent(nameTag -> ((NameTag)nameTag).setComponentSupplier(() -> { + if (ServerInfo.IS_PAPER) { + Component name = ServerInfo.IS_FOLIA ? ModelEngineAPI.getEntityHandler().getCustomName(bukkitTarget) : bukkitTarget.customName(); + return (Component)(name == null ? Component.empty() : name); + } else { + String name = bukkitTarget.getCustomName(); + return name == null ? null : LegacyComponentSerializer.legacyAmpersand().deserialize(name); + } + })); + } + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ModelEngineSupportImpl.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ModelEngineSupportImpl.java new file mode 100644 index 0000000..ec527ec --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ModelEngineSupportImpl.java @@ -0,0 +1,129 @@ +package com.ticxo.modelengine.core21.mythic.compatibility; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.generator.ModelGenerator; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.api.utils.math.TMath; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.adapters.AbstractLocation; +import io.lumine.mythic.api.config.MythicConfig; +import io.lumine.mythic.api.mobs.MythicMob; +import io.lumine.mythic.bukkit.BukkitAdapter; +import io.lumine.mythic.bukkit.MythicBukkit; +import io.lumine.mythic.bukkit.compatibility.AbstractModelEngineSupport; +import io.lumine.mythic.bukkit.compatibility.AbstractModelEngineSupport.MEGAttachment; +import io.lumine.mythic.bukkit.compatibility.AbstractModelEngineSupport.MEGAttachmentData; +import io.lumine.mythic.bukkit.compatibility.AbstractModelEngineSupport.MEGProjectile; +import io.lumine.mythic.bukkit.compatibility.AbstractModelEngineSupport.MEGProjectileData; +import io.lumine.mythic.bukkit.compatibility.AbstractModelEngineSupport.ModelConfig; +import io.lumine.mythic.core.logging.MythicLogger; +import io.lumine.mythic.core.mobs.model.MobModel; +import io.lumine.mythic.core.skills.projectiles.ProjectileBulletableTracker; +import java.util.Map; +import java.util.UUID; +import org.bukkit.entity.Entity; +import org.bukkit.util.BoundingBox; +import org.joml.Vector3f; + +public class ModelEngineSupportImpl extends AbstractModelEngineSupport { + private final Map> trackers = Maps.newConcurrentMap(); + + public ModelEngineSupportImpl() { + super(MythicBukkit.inst()); + } + + public boolean isSubHitbox(UUID uuid) { + return ModelEngineAPI.getInteractionTracker().getHitbox(uuid) != null; + } + + public boolean isBoundToSubHitbox(UUID subHitbox, UUID bound) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(subHitbox); + return hitbox != null && hitbox.getSubHitbox().getBoundEntities().containsKey(bound); + } + + public String getSubHitboxBoneId(UUID uuid) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(uuid); + return hitbox == null ? null : hitbox.getBone().getBoneId(); + } + + public UUID getParentUUID(UUID uuid) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(uuid); + return hitbox == null ? uuid : hitbox.getBone().getActiveModel().getModeledEntity().getBase().getUUID(); + } + + public AbstractEntity getParent(AbstractEntity abstractEntity) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(abstractEntity.getUniqueId()); + if (hitbox == null) { + return abstractEntity; + } else { + return hitbox.getBone().getActiveModel().getModeledEntity().getBase().getOriginal() instanceof Entity entity + ? BukkitAdapter.adapt(entity) + : abstractEntity; + } + } + + public boolean overlapsOOBB(BoundingBox boundingBox, AbstractEntity abstractEntity) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(abstractEntity.getUniqueId()); + if (hitbox == null) { + return false; + } else { + OrientedBoundingBox obb = hitbox.getOrientedBoundingBox(); + return obb != null && obb.intersects(boundingBox); + } + } + + public ModelConfig getBoneModel(String modelId, String boneId) throws IllegalArgumentException { + ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(modelId); + if (blueprint == null) { + throw new IllegalArgumentException("Unknown model " + modelId + "."); + } else { + BlueprintBone blueprintBone = blueprint.getFlatMap().get(boneId); + if (blueprintBone == null) { + throw new IllegalArgumentException("Unknown bone " + boneId + "."); + } else if (!blueprintBone.isRenderer()) { + throw new IllegalArgumentException(boneId + " is not a renderer bone."); + } else { + return new ModelConfig(blueprintBone.getDataId(), blueprintBone.getBaseItem().getMaterial(), false); + } + } + } + + public MobModel createMobModel(MythicMob mythicMob, MythicConfig mythicConfig) { + return new MEGModel(mythicMob, mythicConfig); + } + + public MEGProjectile createMEGBullet(MEGProjectileData model, AbstractLocation location) { + return new ProjectileBullet(model, location); + } + + public MEGAttachment createMEGAttachment(MEGAttachmentData model, AbstractEntity entity) { + return new AuraAttachment(model, entity); + } + + public void queuePostModelRegistration(Runnable runnable) { + ModelEngineAPI.getAPI().getModelGenerator().queueTask(ModelGenerator.Phase.POST_ASSETS, runnable); + } + + public double distanceSquaredToSubHitbox(AbstractLocation abstractLocation, AbstractEntity abstractEntity) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(abstractEntity.getUniqueId()); + OrientedBoundingBox obb = hitbox.getOrientedBoundingBox(); + return obb != null + ? obb.distanceSquared(new Vector3f((float)abstractLocation.getX(), (float)abstractLocation.getY(), (float)abstractLocation.getZ())) + : TMath.distanceSquaredToBoundingBox(abstractLocation.toLocus().toVector(), abstractEntity.getBukkitEntity().getBoundingBox()); + } + + public void load(MythicBukkit mythicBukkit) { + MythicLogger.log("Model Engine Compatibility Loaded."); + } + + public void unload() { + } + + public Map> getTrackers() { + return this.trackers; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MythicCompatibility.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MythicCompatibility.java new file mode 100644 index 0000000..03157e1 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MythicCompatibility.java @@ -0,0 +1,66 @@ +package com.ticxo.modelengine.core21.mythic.compatibility; + +import com.ticxo.modelengine.api.events.ModelDismountEvent; +import com.ticxo.modelengine.api.utils.CompatibilityManager; +import com.ticxo.modelengine.core.ModelEngine; +import com.ticxo.modelengine.core21.mythic.animation.MythicScriptReader; +import com.ticxo.modelengine.core21.mythic.utils.ModelEngineComponentRegistry; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.bukkit.BukkitAdapter; +import io.lumine.mythic.bukkit.MythicBukkit; +import io.lumine.mythic.bukkit.utils.Events; +import io.lumine.mythic.core.skills.EventExecutor; +import io.lumine.mythic.core.skills.SkillTriggers; +import io.lumine.mythic.core.skills.TriggeredSkill; +import java.util.ArrayList; +import java.util.Optional; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +public class MythicCompatibility implements CompatibilityManager.CompatibilityConfiguration { + private final ModelEngine plugin; + private ModelEngineSupportImpl mythicSupport; + private ModelEngineComponentRegistry customComponentRegistry; + + public MythicCompatibility(ModelEngine plugin) { + this.plugin = plugin; + } + + @Override + public boolean tryApply(Plugin plugin) { + this.customComponentRegistry = new ModelEngineComponentRegistry(this.plugin, new ArrayList() { + { + this.add("com.ticxo.modelengine.core21.mythic.conditions"); + this.add("com.ticxo.modelengine.core21.mythic.mechanics"); + this.add("com.ticxo.modelengine.core21.mythic.targeters"); + this.add("com.ticxo.modelengine.core21.mythic.placeholders"); + } + }); + this.plugin.getScriptReaderRegistry().register("mm", new MythicScriptReader()); + this.mythicSupport = new ModelEngineSupportImpl(); + MythicBukkit.inst().getCompatibility().setModelEngine(Optional.of(this.mythicSupport)); + Bukkit.getPluginManager().registerEvents(this.customComponentRegistry, plugin); + this.plugin.getModelGenerator().importModels(true); + Events.subscribe(ModelDismountEvent.class).handler(this::onDismounted); + return true; + } + + void onDismounted(ModelDismountEvent event) { + MythicBukkit.inst().getMobManager().getActiveMob(event.getVehicle().getModeledEntity().getBase().getUUID()).ifPresent(mob -> { + EventExecutor eventBus = MythicBukkit.inst().getSkillManager().getEventBus(); + SkillMetadata data = eventBus.buildSkillMetadata(SkillTriggers.DISMOUNTED, mob, BukkitAdapter.adapt(event.getPassenger()), mob.getLocation(), false); + TriggeredSkill ts = eventBus.processTriggerMechanics(data); + if (ts.getCancelled()) { + event.setCancelled(true); + } + }); + } + + public ModelEngineSupportImpl getMythicSupport() { + return this.mythicSupport; + } + + public ModelEngineComponentRegistry getCustomComponentRegistry() { + return this.customComponentRegistry; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MythicMountController.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MythicMountController.java new file mode 100644 index 0000000..8eb8a9e --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/MythicMountController.java @@ -0,0 +1,68 @@ +package com.ticxo.modelengine.core21.mythic.compatibility; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.impl.AbstractMountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import io.lumine.mythic.api.skills.Skill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.bukkit.BukkitAdapter; +import io.lumine.mythic.bukkit.MythicBukkit; +import io.lumine.mythic.core.skills.variables.VariableRegistry; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; +import org.joml.Vector3f; + +public class MythicMountController extends AbstractMountController { + private final Skill skill; + private final SkillMetadata metadata; + private final VariableRegistry variableRegistry; + + public MythicMountController(Entity entity, Mount mount, Skill skill, SkillMetadata data) { + super(entity, mount); + this.skill = skill; + this.metadata = MythicBukkit.inst() + .getSkillManager() + .getEventBus() + .buildSkillMetadata(data.getCause(), data.getCaster(), data.getTrigger(), data.getOrigin(), !data.isAsync()); + this.metadata.setTrigger(BukkitAdapter.adapt(entity)); + this.variableRegistry = this.metadata.getVariables(); + } + + @Override + public void updateDriverMovement(MoveController controller, ActiveModel model) { + this.callSkillAs(controller, model, "driver"); + } + + @Override + public void updatePassengerMovement(MoveController controller, ActiveModel model) { + this.callSkillAs(controller, model, "passenger"); + } + + public void callSkillAs(MoveController controller, ActiveModel model, String mode) { + if (this.skill.isUsable(this.metadata) && !this.skill.onCooldown(this.metadata.getCaster())) { + Vector3f location = this.getMount().getGlobalLocation(); + this.metadata.setOrigin(BukkitAdapter.adapt(new Location(this.entity.getWorld(), location.x, location.y, location.z))); + this.metadata.setMetadata("meg:active_model", model); + this.metadata.setMetadata("meg:move_controller", controller); + this.variableRegistry.putString("meg:rider", mode); + this.variableRegistry.putFloat("meg:front", this.input.getFront()); + this.variableRegistry.putFloat("meg:side", this.input.getSide()); + this.variableRegistry.putFloat("meg:forward", this.input.isForward() ? 1.0F : 0.0F); + this.variableRegistry.putFloat("meg:backward", this.input.isBackward() ? 1.0F : 0.0F); + this.variableRegistry.putFloat("meg:left", this.input.isLeft() ? 1.0F : 0.0F); + this.variableRegistry.putFloat("meg:right", this.input.isRight() ? 1.0F : 0.0F); + this.variableRegistry.putInt("meg:jump", this.input.isJump() ? 1 : 0); + this.variableRegistry.putInt("meg:sneak", this.input.isSneak() ? 1 : 0); + this.variableRegistry.putInt("meg:sprint", this.input.isSprint() ? 1 : 0); + this.variableRegistry.putInt("meg:on_ground", controller.isOnGround() ? 1 : 0); + this.variableRegistry.putFloat("meg:speed", controller.getSpeed()); + Vector vector = controller.getVelocity(); + this.variableRegistry.putFloat("meg:vx", (float)vector.getX()); + this.variableRegistry.putFloat("meg:vy", (float)vector.getY()); + this.variableRegistry.putFloat("meg:vz", (float)vector.getZ()); + this.skill.execute(this.metadata); + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileBullet.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileBullet.java new file mode 100644 index 0000000..b222084 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileBullet.java @@ -0,0 +1,160 @@ +package com.ticxo.modelengine.core21.mythic.compatibility; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.BlueprintAnimation; +import com.ticxo.modelengine.api.animation.handler.AnimationHandler; +import com.ticxo.modelengine.api.animation.handler.IStateMachineHandler; +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.animation.property.SimpleProperty; +import com.ticxo.modelengine.api.entity.Dummy; +import com.ticxo.modelengine.api.entity.data.DummyEntityData; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.Segment; +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import io.lumine.mythic.api.adapters.AbstractLocation; +import io.lumine.mythic.api.adapters.AbstractVector; +import io.lumine.mythic.bukkit.BukkitAdapter; +import io.lumine.mythic.bukkit.compatibility.AbstractModelEngineSupport.MEGProjectile; +import io.lumine.mythic.bukkit.compatibility.AbstractModelEngineSupport.MEGProjectileData; +import io.lumine.mythic.core.logging.MythicLogger; +import java.util.UUID; +import java.util.Map.Entry; +import org.bukkit.Color; + +public class ProjectileBullet implements MEGProjectile { + private Dummy entity = new Dummy(); + private ModelBlueprint modelBlueprint; + private ActiveModel activeModel; + private ModeledEntity modeledEntity; + + public ProjectileBullet(MEGProjectileData modelData, AbstractLocation location) { + String modelId = modelData.getModelId(); + String state = modelData.getState(); + double scale = modelData.getScale(); + String color = modelData.getColor(); + boolean enchanted = modelData.isEnchanted(); + boolean glowing = modelData.isGlowing(); + String glowColor = modelData.getGlowColor(); + Integer brightness = modelData.getBrightness(); + this.entity.setLocation(BukkitAdapter.adapt(location)); + this.modelBlueprint = ModelEngineAPI.getBlueprint(modelId); + if (this.modelBlueprint == null) { + MythicLogger.error("Failed to spawn Projectile Bullet: Model " + modelId + " not found"); + } else { + this.modeledEntity = ModelEngineAPI.createModeledEntity(this.entity); + this.activeModel = ModelEngineAPI.createActiveModel(this.modelBlueprint); + this.activeModel.setScale(scale); + this.activeModel.setHitboxScale(0.0); + if (color != null) { + if (color.startsWith("#")) { + color = color.substring(1); + } + + this.activeModel.setDefaultTint(Color.fromRGB(Integer.parseInt(color, 16))); + } + + if (glowing) { + this.activeModel.setGlowing(true); + if (glowColor != null) { + if (glowColor.startsWith("#")) { + glowColor = glowColor.substring(1); + } + + this.activeModel.setGlowColor(Integer.parseInt(glowColor, 16)); + } + } + + if (brightness != null) { + this.activeModel.setBlockLight(brightness); + this.activeModel.setSkyLight(brightness); + } + + this.modeledEntity.getAnimationLodHandler().setEnabled(modelData.isUseALOD()); + this.modeledEntity.addModel(this.activeModel, true); + BodyRotationController rotationController = this.modeledEntity.getBase().getBodyRotationController(); + rotationController.setMaxHeadAngle(0.0F); + rotationController.setMinHeadAngle(0.0F); + rotationController.setMaxBodyAngle(0.0F); + rotationController.setMinBodyAngle(0.0F); + rotationController.setRotationDelay(0); + rotationController.setRotationDuration(0); + + for (Entry entry : this.activeModel.getBones().entrySet()) { + ModelBone bone = entry.getValue(); + if (enchanted) { + bone.setEnchanted(true); + } + + bone.getBoneBehavior(BoneBehaviorTypes.SEGMENT).ifPresent(segment -> ((Segment)segment).setBounded(false)); + } + + if (state != null) { + AnimationHandler handler = this.activeModel.getAnimationHandler(); + if (handler instanceof IStateMachineHandler stateMachineHandler) { + IAnimationProperty property = stateMachineHandler.playAnimation(100, state, 0.0, 0.0, 1.0, true); + if (property != null) { + property.setForceLoopMode(BlueprintAnimation.LoopMode.LOOP); + } + } else { + IAnimationProperty property = handler.playAnimation(state, 0.0, 0.0, 1.0, true); + if (property != null) { + property.setForceLoopMode(BlueprintAnimation.LoopMode.LOOP); + } + } + } + } + } + + public UUID getEntityId() { + return this.entity.getUUID(); + } + + public void setLocation(AbstractLocation location) { + this.entity.setLocation(BukkitAdapter.adapt(location)); + } + + public void setDirection(AbstractVector direction) { + double yaw = Math.toDegrees(Math.atan2(-direction.getX(), direction.getZ())); + double pitch = -Math.toDegrees(Math.asin(direction.getY() / direction.length())); + this.entity.setXHeadRot((float)pitch); + this.entity.setYHeadRot((float)yaw); + this.entity.setYBodyRot((float)yaw); + } + + public void setRenderRadius(int radius) { + DummyEntityData data = this.entity.getData(); + data.setRenderRadius(radius); + } + + public void disableCulling() { + DummyEntityData data = this.entity.getData(); + data.setVerticalCull(false); + data.setBackCull(false); + data.setBlockedCull(false); + data.cullUpdate(); + } + + public void close() throws Exception { + BlueprintAnimation animation = this.modelBlueprint.getAnimations().get("death"); + if (animation == null) { + ModelEngineAPI.removeModeledEntity(this.entity.getUUID()); + this.entity.setRemoved(true); + } else { + SimpleProperty property = new SimpleProperty(this.activeModel, animation, 0.0, 0.0, 1.0); + property.setForceLoopMode(BlueprintAnimation.LoopMode.ONCE); + property.setForceOverride(BlueprintAnimation.OverrideMode.OVERRIDE); + property.setOnEndTask(() -> { + ModelEngineAPI.removeModeledEntity(this.entity.getUUID()); + this.entity.setRemoved(true); + }); + if (!this.activeModel.getAnimationHandler().playAnimation(property, true)) { + ModelEngineAPI.removeModeledEntity(this.entity.getUUID()); + this.entity.setRemoved(true); + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileData.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileData.java new file mode 100644 index 0000000..5fc1e22 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileData.java @@ -0,0 +1,176 @@ +package com.ticxo.modelengine.core21.mythic.compatibility; + +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.cull.BasicCulling; +import com.ticxo.modelengine.api.entity.cull.ModelCuller; +import com.ticxo.modelengine.api.entity.data.AbstractEntityData; +import com.ticxo.modelengine.api.entity.data.TrackingMap; +import io.lumine.mythic.api.skills.IParentSkill; +import io.lumine.mythic.bukkit.BukkitAdapter; +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 java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +public class ProjectileData extends AbstractEntityData { + private final ProjectileEntity projectileEntity; + protected final ModelCuller culler; + private final AtomicBoolean isAlive = new AtomicBoolean(true); + private final AtomicReference location = new AtomicReference<>(); + private final Set syncTracking = new HashSet<>(); + private final TrackingMap trackingMap = new TrackingMap(); + private final Map asyncTracking = this.trackingMap; + private final Queue startTrackingQueue = new ConcurrentLinkedQueue<>(); + private final Set startTracking = new HashSet<>(); + private final Queue stopTrackingQueue = new ConcurrentLinkedQueue<>(); + private final Set stopTracking = new HashSet<>(); + + public ProjectileData(ProjectileEntity projectileEntity) { + this(projectileEntity, new BasicCulling()); + } + + public ProjectileData(ProjectileEntity projectileEntity, ModelCuller culler) { + this.projectileEntity = projectileEntity; + this.culler = culler; + culler.setData(this); + 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); + } + } + } + + @Override + public void syncUpdate() { + Location location = BukkitAdapter.adapt(this.projectileEntity.getOriginal().getCurrentLocation()); + this.location.set(location); + this.isAlive.set(!((IParentSkill)this.projectileEntity.getOriginal()).getCancelled()); + if (!this.isDataValid()) { + this.projectileEntity.removeSelf(); + } + + HashSet updatedTracking = new HashSet<>(); + int radiusSqr = this.projectileEntity.getRenderRadius() * this.projectileEntity.getRenderRadius(); + World world = location.getWorld(); + double lx = location.getX(); + double ly = location.getY(); + double lz = location.getZ(); + + for (Player player : Bukkit.getOnlinePlayers()) { + if (world.equals(player.getWorld())) { + double dx = player.getX() - lx; + double dy = player.getY() - ly; + double dz = player.getZ() - lz; + if (dx * dx + dy * dy + dz * dz <= radiusSqr) { + updatedTracking.add(player.getUniqueId()); + } + } + } + + for (UUID playerx : updatedTracking) { + if (!this.syncTracking.contains(playerx)) { + this.startTrackingQueue.add(playerx); + } + } + + for (UUID playerxx : this.syncTracking) { + if (!updatedTracking.contains(playerxx)) { + this.stopTrackingQueue.add(playerxx); + } + } + + this.syncTracking.clear(); + this.syncTracking.addAll(updatedTracking); + } + + @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.projectileEntity; + } + + @Override + public boolean isDataValid() { + return this.isAlive.get(); + } + + @Override + public Location getLocation() { + return this.location.get(); + } + + @Override + public List getPassengers() { + return List.of(); + } + + @Override + public Set getStartTracking() { + return ImmutableSet.copyOf(this.startTracking); + } + + @Override + public Map getMutableTracking() { + return this.asyncTracking; + } + + @Override + public Map getTracking() { + return this.trackingMap.snapshot(); + } + + @Override + public Set getStopTracking() { + return ImmutableSet.copyOf(this.stopTracking); + } + + @Override + public boolean hasTracking() { + return !this.asyncTracking.isEmpty(); + } + + @Override + public boolean isBaseGlowing() { + return false; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileEntity.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileEntity.java new file mode 100644 index 0000000..95668e1 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/compatibility/ProjectileEntity.java @@ -0,0 +1,232 @@ +package com.ticxo.modelengine.core21.mythic.compatibility; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +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.EmptyBodyRotationController; +import com.ticxo.modelengine.api.nms.impl.EmptyLookController; +import com.ticxo.modelengine.api.nms.impl.EmptyMoveController; +import com.ticxo.modelengine.core21.Java21Helper; +import io.lumine.mythic.api.adapters.AbstractVector; +import io.lumine.mythic.api.skills.IParentSkill; +import io.lumine.mythic.core.skills.projectiles.ProjectileBulletableTracker; +import io.lumine.mythic.core.skills.projectiles.Projectile.ProjectileTracker; +import java.util.UUID; +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 class ProjectileEntity implements BaseEntity { + private final T original; + private final ProjectileData data; + private final int entityId; + private final UUID uuid; + private final BodyRotationController bodyRotationController = new EmptyBodyRotationController(); + private final MoveController moveController = new EmptyMoveController(); + private final LookController lookController = new EmptyLookController(); + private int renderRadius = 32; + + public ProjectileEntity(T original) { + this.original = original; + this.entityId = ModelEngineAPI.getEntityHandler().getNextEntityId(); + this.uuid = UUID.randomUUID(); + this.data = new ProjectileData(this); + Java21Helper.getMythicCompatibility().getMythicSupport().getTrackers().put(original, this); + } + + @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 isRemoved() { + return !this.data.isDataValid(); + } + + @Override + public boolean isAlive() { + return this.data.isDataValid(); + } + + @Override + public boolean isForcedAlive() { + return false; + } + + @Override + public void setForcedAlive(boolean flag) { + } + + @Override + public UUID getUUID() { + return this.uuid; + } + + @Override + public double getMaxStepHeight() { + return 0.0; + } + + @Override + public void setMaxStepHeight(double stepHeight) { + } + + @Override + public void setCollidableWith(Entity entity, boolean flag) { + } + + @Override + public boolean isGlowing() { + return false; + } + + @Override + public int getGlowColor() { + return -1; + } + + @Override + public boolean isOnFire() { + return false; + } + + @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 null; + } + + @Override + public EntityHandler.InteractionResult interact(HitboxEntity hitbox, HumanEntity player, EquipmentSlot slot) { + return null; + } + + @Override + public float getYRot() { + AbstractVector vel = this.original.getCurrentVelocity(); + return vel == null ? 0.0F : (float)Math.toDegrees(Math.atan2(-vel.getX(), vel.getZ())); + } + + @Override + public float getYHeadRot() { + return this.getYRot(); + } + + @Override + public float getXHeadRot() { + AbstractVector vel = this.original.getCurrentVelocity(); + if (vel == null) { + return 0.0F; + } else { + double hMag = Math.sqrt(vel.getX() * vel.getX() + vel.getZ() * vel.getZ()); + return (float)Math.toDegrees(-Math.atan2(vel.getY(), hMag)); + } + } + + @Override + public float getYBodyRot() { + return this.getYRot(); + } + + @Override + public boolean isWalking() { + return false; + } + + @Override + public boolean isStrafing() { + return false; + } + + @Override + public boolean isJumping() { + return false; + } + + @Override + public boolean isFlying() { + return false; + } + + @Override + public float getHealth() { + return 0.0F; + } + + @Override + public float getMaxHealth() { + return 0.0F; + } + + @Override + public BoundingBox getBoundingBox() { + return this.original instanceof ProjectileTracker tracker ? tracker.getHitbox() : new BoundingBox(); + } + + public void removeSelf() { + Java21Helper.getMythicCompatibility().getMythicSupport().getTrackers().remove(this.original, this); + } + + public T getOriginal() { + return this.original; + } + + public ProjectileData getData() { + return this.data; + } + + @Override + public int getEntityId() { + return this.entityId; + } + + @Override + public BodyRotationController getBodyRotationController() { + return this.bodyRotationController; + } + + @Override + public MoveController getMoveController() { + return this.moveController; + } + + @Override + public LookController getLookController() { + return this.lookController; + } + + @Override + public int getRenderRadius() { + return this.renderRadius; + } + + @Override + public void setRenderRadius(int renderRadius) { + this.renderRadius = renderRadius; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HasModelCondition.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HasModelCondition.java new file mode 100644 index 0000000..73f9bc6 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HasModelCondition.java @@ -0,0 +1,51 @@ +package com.ticxo.modelengine.core21.mythic.conditions; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicCondition; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.conditions.IEntityCondition; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; + +@MythicCondition( + name = "hasmodel" +) +public class HasModelCondition implements IEntityCondition { + private final PlaceholderString modelId; + private final PlaceholderString state; + + public HasModelCondition(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.state = mlc.getPlaceholderString(new String[]{"s", "state"}, null, new String[0]); + } + + public boolean check(AbstractEntity abstractEntity) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(abstractEntity.getUniqueId()); + if (modeledEntity == null) { + return false; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, abstractEntity); + String state = MythicUtils.getOrNullLowercase(this.state, abstractEntity); + if (modelId == null) { + if (state == null) { + return !modeledEntity.getModels().isEmpty(); + } else { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + if (activeModel.getAnimationHandler().isPlayingAnimation(state)) { + return true; + } + } + + return false; + } + } else { + Optional maybeModel = modeledEntity.getModel(modelId); + return maybeModel.isEmpty() ? false : state == null || maybeModel.get().getAnimationHandler().isPlayingAnimation(state); + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HitboxCondition.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HitboxCondition.java new file mode 100644 index 0000000..159d2f1 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HitboxCondition.java @@ -0,0 +1,30 @@ +package com.ticxo.modelengine.core21.mythic.conditions; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.core21.mythic.utils.MythicCondition; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.conditions.ISkillMetaCondition; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.bukkit.events.MythicConditionLoadEvent; + +@MythicCondition( + name = "hitbox" +) +public class HitboxCondition implements ISkillMetaCondition { + private PlaceholderString hitbox; + + public HitboxCondition(ModelEngineAPI plugin, MythicConditionLoadEvent loader) { + MythicLineConfig config = loader.getConfig(); + this.hitbox = config.getPlaceholderString(new String[]{"hitbox", "hb", "h", "ob"}, loader.getArgument(), new String[0]); + } + + public boolean check(SkillMetadata skillMetadata) { + if (!skillMetadata.getVariables().has("hitbox")) { + return false; + } else { + String hitbox = skillMetadata.getVariables().getString("hitbox"); + return hitbox.equalsIgnoreCase(this.hitbox.get(skillMetadata)); + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HitboxIsSubHitboxCondition.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HitboxIsSubHitboxCondition.java new file mode 100644 index 0000000..8a4e6d9 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/HitboxIsSubHitboxCondition.java @@ -0,0 +1,31 @@ +package com.ticxo.modelengine.core21.mythic.conditions; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.core21.mythic.utils.MythicCondition; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.conditions.ISkillMetaCondition; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.bukkit.events.MythicConditionLoadEvent; + +@MythicCondition( + name = "hitboxissubhitbox", + aliases = {"issubhitbox"} +) +public class HitboxIsSubHitboxCondition implements ISkillMetaCondition { + private PlaceholderString hitbox; + + public HitboxIsSubHitboxCondition(ModelEngineAPI plugin, MythicConditionLoadEvent loader) { + MythicLineConfig config = loader.getConfig(); + this.hitbox = config.getPlaceholderString(new String[]{"hitbox", "hb", "h", "ob"}, loader.getArgument(), new String[0]); + } + + public boolean check(SkillMetadata skillMetadata) { + if (!skillMetadata.getVariables().has("hitbox")) { + return false; + } else { + String hitbox = skillMetadata.getVariables().getString("hitbox"); + return hitbox.equalsIgnoreCase(this.hitbox.get(skillMetadata)); + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/IsDrivingModelCondition.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/IsDrivingModelCondition.java new file mode 100644 index 0000000..2e96346 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/IsDrivingModelCondition.java @@ -0,0 +1,31 @@ +package com.ticxo.modelengine.core21.mythic.conditions; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.core21.mythic.utils.MythicCondition; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.skills.conditions.IEntityCondition; + +@MythicCondition( + name = "drivingmodel" +) +public class IsDrivingModelCondition implements IEntityCondition { + public boolean check(AbstractEntity abstractEntity) { + ActiveModel model = ModelEngineAPI.getMountPairManager().getMountedPair(abstractEntity.getUniqueId()); + if (model == null) { + return false; + } else { + ModeledEntity modeledEntity = model.getModeledEntity(); + if (modeledEntity == null) { + return false; + } else { + BehaviorManager mountManager = ((MountData)modeledEntity.getMountData()).getMainMountManager(); + return mountManager == null ? false : ((MountManager)mountManager).getDriver() == abstractEntity.getBukkitEntity(); + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/IsRidingModelCondition.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/IsRidingModelCondition.java new file mode 100644 index 0000000..91c4365 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/IsRidingModelCondition.java @@ -0,0 +1,31 @@ +package com.ticxo.modelengine.core21.mythic.conditions; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.core21.mythic.utils.MythicCondition; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.skills.conditions.IEntityCondition; +import java.util.Optional; + +@MythicCondition( + name = "ridingmodel" +) +public class IsRidingModelCondition implements IEntityCondition { + public boolean check(AbstractEntity abstractEntity) { + ActiveModel model = ModelEngineAPI.getMountPairManager().getMountedPair(abstractEntity.getUniqueId()); + if (model == null) { + return false; + } else { + Optional maybeManager = model.getMountManager(); + if (maybeManager.isEmpty()) { + return false; + } else { + BehaviorManager mountManager = (BehaviorManager)maybeManager.get(); + Optional mount = ((MountManager)mountManager).getMount(abstractEntity.getBukkitEntity()); + return mount.isPresent() && mount.get() != ((MountManager)mountManager).getDriverBone(); + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/ModelHasDriverCondition.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/ModelHasDriverCondition.java new file mode 100644 index 0000000..263b06a --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/ModelHasDriverCondition.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.core21.mythic.conditions; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.core21.mythic.utils.MythicCondition; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.skills.conditions.IEntityCondition; +import java.util.Optional; + +@MythicCondition( + name = "modelhasdriver", + aliases = {"modeldriver"} +) +public class ModelHasDriverCondition implements IEntityCondition { + public boolean check(AbstractEntity abstractEntity) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(abstractEntity.getUniqueId()); + if (modeledEntity == null) { + return false; + } else { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + Optional maybeMountManager = activeModel.getMountManager(); + if (!maybeMountManager.isEmpty() && ((MountManager)((BehaviorManager)maybeMountManager.get())).isControlled()) { + return true; + } + } + + return false; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/ModelHasPassengerCondition.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/ModelHasPassengerCondition.java new file mode 100644 index 0000000..f6ca66c --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/conditions/ModelHasPassengerCondition.java @@ -0,0 +1,155 @@ +package com.ticxo.modelengine.core21.mythic.conditions; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicCondition; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.conditions.IEntityCondition; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Locale; +import java.util.Optional; + +@MythicCondition( + name = "modelhaspassengers", + aliases = {"modelhaspassenger", "modelpassengers", "modelpassenger"} +) +public class ModelHasPassengerCondition implements IEntityCondition { + private final PlaceholderString modelId; + private final PlaceholderString pbone; + private final String mode; + + public ModelHasPassengerCondition(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.pbone = mlc.getPlaceholderString(new String[]{"p", "pbone", "seat"}, null, new String[0]); + this.mode = mlc.getString(new String[]{"mode"}, "AND", new String[0]).toUpperCase(Locale.ENGLISH); + } + + public boolean check(AbstractEntity abstractEntity) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(abstractEntity.getUniqueId()); + if (modeledEntity == null) { + return false; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, abstractEntity); + if (modelId == null) { + return this.noModelIdCheck(modeledEntity, abstractEntity); + } else { + Optional maybeModel = modeledEntity.getModel(modelId); + if (maybeModel.isEmpty()) { + return false; + } else { + ActiveModel activeModel = maybeModel.get(); + Optional maybeMountManager = activeModel.getMountManager(); + if (maybeMountManager.isEmpty()) { + return false; + } else { + BehaviorManager mountManager = (BehaviorManager)maybeMountManager.get(); + String pBone = MythicUtils.getOrNullLowercase(this.pbone, abstractEntity); + if (pBone != null && !pBone.isBlank()) { + String[] seats = pBone.split(","); + String var10 = this.mode; + switch (var10) { + case "OR": + for (String seatId : seats) { + Optional maybeSeatx = ((MountManager)mountManager).getSeat(seatId); + if (!maybeSeatx.isEmpty() + && ((MountManager)mountManager).getDriverBone() != maybeSeatx.get() + && !((Mount)((BoneBehavior)maybeSeatx.get())).getPassengers().isEmpty()) { + return true; + } + } + + return false; + case "AND": + for (String seatId : seats) { + Optional maybeSeat = ((MountManager)mountManager).getSeat(seatId); + if (maybeSeat.isEmpty()) { + return false; + } + + if (((MountManager)mountManager).getDriverBone() != maybeSeat.get() + && ((Mount)((BoneBehavior)maybeSeat.get())).getPassengers().isEmpty()) { + return false; + } + } + + return true; + default: + return false; + } + } else { + return ((MountManager)mountManager).hasPassengers(); + } + } + } + } + } + } + + private boolean noModelIdCheck(ModeledEntity modeledEntity, AbstractEntity abstractEntity) { + String pBone = MythicUtils.getOrNullLowercase(this.pbone, abstractEntity); + if (pBone != null && !pBone.isBlank()) { + String[] seats = pBone.split(","); + String var17 = this.mode; + switch (var17) { + case "OR": + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + Optional maybeMountManager = activeModel.getMountManager(); + if (!maybeMountManager.isEmpty()) { + BehaviorManager mountManager = (BehaviorManager)maybeMountManager.get(); + + for (String seatId : seats) { + Optional maybeSeat = ((MountManager)mountManager).getSeat(seatId); + if (!maybeSeat.isEmpty() + && ((MountManager)mountManager).getDriverBone() != maybeSeat.get() + && !((Mount)((BoneBehavior)maybeSeat.get())).getPassengers().isEmpty()) { + return true; + } + } + } + } + + return false; + case "AND": + for (ActiveModel activeModelx : modeledEntity.getModels().values()) { + Optional maybeMountManager = activeModelx.getMountManager(); + if (maybeMountManager.isEmpty()) { + return false; + } + + BehaviorManager mountManager = (BehaviorManager)maybeMountManager.get(); + + for (String seatIdx : seats) { + Optional maybeSeat = ((MountManager)mountManager).getSeat(seatIdx); + if (maybeSeat.isEmpty()) { + return false; + } + + if (((MountManager)mountManager).getDriverBone() != maybeSeat.get() && ((Mount)((BoneBehavior)maybeSeat.get())).getPassengers().isEmpty()) { + return false; + } + } + } + + return true; + default: + return false; + } + } else { + for (ActiveModel activeModelx : modeledEntity.getModels().values()) { + Optional maybeMountManager = activeModelx.getMountManager(); + if (!maybeMountManager.isEmpty() && ((MountManager)((BehaviorManager)maybeMountManager.get())).hasPassengers()) { + return true; + } + } + + return false; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/AnimateModelMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/AnimateModelMechanic.java new file mode 100644 index 0000000..6554de0 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/AnimateModelMechanic.java @@ -0,0 +1,201 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +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.model.bone.SimpleManualAnimator; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Locale; +import java.util.Optional; +import java.util.Map.Entry; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +@MythicMechanic( + name = "animatemodel", + aliases = {} +) +public class AnimateModelMechanic implements ITargetedEntitySkill, INoTargetSkill { + private static final String[] POSITION = new String[]{"pos", "position"}; + private static final String[] ROTATION = new String[]{"rot", "rotation"}; + private static final String[] SCALE = new String[]{"scl", "scale"}; + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final boolean exactMatch; + private final boolean relative; + private final boolean override; + private final boolean copy; + private final PlaceholderDouble[] position = new PlaceholderDouble[3]; + private final boolean hasPosition; + private final PlaceholderDouble[] rotation = new PlaceholderDouble[3]; + private final boolean hasRotation; + private final PlaceholderDouble[] scale = new PlaceholderDouble[3]; + private final boolean hasScale; + private final PlaceholderString rotationModeString; + private AnimateModelMechanic.RotationMode rotationMode; + + public AnimateModelMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, "", new String[0]); + this.exactMatch = mlc.getBoolean(new String[]{"em", "exact", "match", "exactmatch"}, true); + this.relative = mlc.getBoolean(new String[]{"r", "rel", "relative"}, false); + this.override = mlc.getBoolean(new String[]{"o", "ov", "override"}, false); + this.copy = mlc.getBoolean(new String[]{"copy"}, true); + this.hasPosition = this.readTransform(mlc, POSITION, this.position, "position", "0"); + this.hasRotation = this.readTransform(mlc, ROTATION, this.rotation, "rotation", "0"); + this.hasScale = this.readTransform(mlc, SCALE, this.scale, "scale", "1"); + this.rotationModeString = mlc.getPlaceholderString(new String[]{"rm", "rotmode"}, "LOCAL", new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + this.rotationMode = AnimateModelMechanic.RotationMode.get(this.rotationModeString.get(meta, target).toUpperCase(Locale.ENGLISH)); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.transform(activeModel, partId, meta, target)); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + this.rotationMode = AnimateModelMechanic.RotationMode.get(this.rotationModeString.get(meta).toUpperCase(Locale.ENGLISH)); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.transform(activeModel, partId, meta, null)); + return SkillResult.SUCCESS; + } + } + + private boolean readTransform(MythicLineConfig mlc, String[] attrs, PlaceholderDouble[] axis, String axisName, String def) { + String coords = mlc.getString(attrs, null, new String[0]); + if (coords == null) { + return false; + } else { + String[] split = coords.split(","); + + try { + axis[0] = PlaceholderDouble.of(split[0]); + axis[1] = PlaceholderDouble.of(split[1]); + axis[2] = PlaceholderDouble.of(split[2]); + } catch (Exception var9) { + TLogger.error("The '" + axisName + "' attribute must be in the format " + axisName + "=x,y,z."); + axis[0] = PlaceholderDouble.of(def); + axis[1] = PlaceholderDouble.of(def); + axis[2] = PlaceholderDouble.of(def); + } + + return true; + } + } + + private void transform(ActiveModel activeModel, String partId, SkillMetadata meta, AbstractEntity target) { + if (this.override) { + if (this.exactMatch) { + activeModel.getBone(partId).ifPresent(bone -> this.transform(this.getAnimator(bone), meta, target)); + return; + } + + for (Entry entry : activeModel.getBones().entrySet()) { + if (entry.getKey().contains(partId)) { + this.transform(this.getAnimator(entry.getValue()), meta, target); + } + } + } else { + if (this.exactMatch) { + activeModel.getBone(partId).ifPresent(bone -> bone.setManualAnimator(null)); + return; + } + + for (Entry entryx : activeModel.getBones().entrySet()) { + if (entryx.getKey().contains(partId)) { + entryx.getValue().setManualAnimator(null); + } + } + } + } + + private SimpleManualAnimator getAnimator(ModelBone bone) { + if (bone.getManualAnimator() instanceof SimpleManualAnimator animator) { + return animator; + } else { + SimpleManualAnimator a = this.copy ? new SimpleManualAnimator(bone) : new SimpleManualAnimator(); + bone.setManualAnimator(a); + return a; + } + } + + private void transform(SimpleManualAnimator animator, SkillMetadata meta, AbstractEntity target) { + this.transform(this.hasPosition, animator.getPosition(), this.position, meta, target); + this.transformRotation(this.hasRotation, animator.getRotation(), this.rotation, meta, target); + this.transform(this.hasScale, animator.getScale(), this.scale, meta, target); + } + + private void transform(boolean hasValue, Vector3f data, PlaceholderDouble[] values, SkillMetadata meta, AbstractEntity target) { + if (hasValue) { + if (this.relative) { + data.add((float)values[0].get(meta, target), (float)values[1].get(meta, target), (float)values[2].get(meta, target)); + } else { + data.set((float)values[0].get(meta, target), (float)values[1].get(meta, target), (float)values[2].get(meta, target)); + } + } + } + + private void transformRotation(boolean hasValue, Quaternionf data, PlaceholderDouble[] values, SkillMetadata meta, AbstractEntity target) { + if (hasValue) { + Quaternionf delta = new Quaternionf() + .rotationZYX( + (float)values[2].get(meta, target) * (float) (Math.PI / 180.0), + (float)values[1].get(meta, target) * (float) (Math.PI / 180.0), + (float)values[0].get(meta, target) * (float) (Math.PI / 180.0) + ); + if (this.relative) { + switch (this.rotationMode) { + case LOCAL: + data.mul(delta); + break; + case GLOBAL: + delta.mul(data, data); + } + } else { + data.set(delta); + } + } + } + + static enum RotationMode { + LOCAL, + GLOBAL; + + static AnimateModelMechanic.RotationMode get(String value) { + try { + return valueOf(value); + } catch (Exception var2) { + return LOCAL; + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/BillboardMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/BillboardMechanic.java new file mode 100644 index 0000000..1350c60 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/BillboardMechanic.java @@ -0,0 +1,99 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +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.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Locale; +import java.util.Optional; +import java.util.Map.Entry; +import org.bukkit.entity.Display.Billboard; + +@MythicMechanic( + name = "billboard", + aliases = {} +) +public class BillboardMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderString billboard; + private final boolean exactMatch; + private final boolean child; + + public BillboardMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, "", new String[0]); + this.billboard = mlc.getPlaceholderString(new String[]{"b", "bb", "bill", "billboard"}, null, new String[0]); + this.exactMatch = mlc.getBoolean(new String[]{"em", "exact", "match", "exactmatch"}, true); + this.child = mlc.getBoolean(new String[]{"c", "child"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + + try { + String billboard = MythicUtils.getOrNull(this.billboard, meta, target).toUpperCase(Locale.ENGLISH); + Billboard bb = Billboard.valueOf(billboard); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.billboard(activeModel, partId, bb)); + return SkillResult.SUCCESS; + } catch (Exception var9) { + var9.printStackTrace(); + return SkillResult.ERROR; + } + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + + try { + String billboard = MythicUtils.getOrNull(this.billboard, meta).toUpperCase(Locale.ENGLISH); + Billboard bb = Billboard.valueOf(billboard); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.billboard(activeModel, partId, bb)); + return SkillResult.SUCCESS; + } catch (Exception var8) { + var8.printStackTrace(); + return SkillResult.ERROR; + } + } + } + + private void billboard(ActiveModel activeModel, String partId, Billboard billboard) { + if (partId.isBlank()) { + activeModel.setBillboard(billboard); + } else if (this.exactMatch) { + activeModel.getBone(partId).ifPresent(bone -> MythicUtils.executeBoneChild(this.child, bone, v -> v.setBillboard(billboard))); + } else { + for (Entry entry : activeModel.getBones().entrySet()) { + if (entry.getKey().contains(partId)) { + MythicUtils.executeBoneChild(this.child, entry.getValue(), bone -> bone.setBillboard(billboard)); + } + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/BrightnessMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/BrightnessMechanic.java new file mode 100644 index 0000000..e288b48 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/BrightnessMechanic.java @@ -0,0 +1,99 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +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.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; +import java.util.Map.Entry; + +@MythicMechanic( + name = "brightness", + aliases = {"light"} +) +public class BrightnessMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderInt blockLight; + private final PlaceholderInt skyLight; + private final boolean exactMatch; + private final boolean child; + + public BrightnessMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, "", new String[0]); + this.blockLight = mlc.getPlaceholderInteger(new String[]{"block", "b"}, -1, new String[0]); + this.skyLight = mlc.getPlaceholderInteger(new String[]{"sky", "s"}, -1, new String[0]); + this.exactMatch = mlc.getBoolean(new String[]{"em", "exact", "match", "exactmatch"}, true); + this.child = mlc.getBoolean(new String[]{"c", "child"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + int block = this.blockLight.get(meta, target); + int sky = this.skyLight.get(meta, target); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.light(activeModel, partId, block, sky)); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeBullet = meta.getMetadata("bullet"); + if (maybeBullet.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + Optional maybeModel = MythicUtils.getParentVFXModel(meta); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + int block = this.blockLight.get(meta); + int sky = this.skyLight.get(meta); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.light(activeModel, partId, block, sky)); + return SkillResult.SUCCESS; + } + } + } + + private void light(ActiveModel activeModel, String partId, int block, int sky) { + if (partId.isBlank()) { + activeModel.setBlockLight(block); + activeModel.setSkyLight(sky); + } else if (this.exactMatch) { + activeModel.getBone(partId).ifPresent(bone -> MythicUtils.executeBoneChild(this.child, bone, v -> this.setLight(v, block, sky))); + } else { + for (Entry entry : activeModel.getBones().entrySet()) { + if (entry.getKey().contains(partId)) { + MythicUtils.executeBoneChild(this.child, entry.getValue(), bone -> this.setLight(bone, block, sky)); + } + } + } + } + + private void setLight(ModelBone bone, int block, int sky) { + bone.setBlockLight(block); + bone.setSkyLight(sky); + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ChangeParentMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ChangeParentMechanic.java new file mode 100644 index 0000000..1b44de1 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ChangeParentMechanic.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; + +@MythicMechanic( + name = "changeparent", + aliases = {} +) +public class ChangeParentMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString parentPart; + private final PlaceholderString childPart; + + public ChangeParentMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.parentPart = mlc.getPlaceholderString(new String[]{"p", "parent"}, null, new String[0]); + this.childPart = mlc.getPlaceholderString(new String[]{"c", "child"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + ActiveModel activeModel = MythicUtils.getActiveModelOrNull(model, modelId); + if (activeModel == null) { + return SkillResult.CONDITION_FAILED; + } else { + String parentPart = MythicUtils.getOrNullLowercase(this.parentPart, meta, target); + String childPart = MythicUtils.getOrNullLowercase(this.childPart, meta, target); + activeModel.getBone(parentPart) + .ifPresent(parent -> activeModel.getBone(childPart).ifPresent(child -> model.registerTickTask(ModeledEntity.Phase.PRE_MODEL_TICK, entity -> { + child.setParent(parent); + return true; + }))); + return SkillResult.SUCCESS; + } + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + ActiveModel activeModel = MythicUtils.getActiveModelOrNull(model, modelId); + if (activeModel == null) { + return SkillResult.CONDITION_FAILED; + } else { + String parentPart = MythicUtils.getOrNullLowercase(this.parentPart, meta); + String childPart = MythicUtils.getOrNullLowercase(this.childPart, meta); + activeModel.getBone(parentPart) + .ifPresent(parent -> activeModel.getBone(childPart).ifPresent(child -> model.registerTickTask(ModeledEntity.Phase.PRE_MODEL_TICK, entity -> { + child.setParent(parent); + return true; + }))); + return SkillResult.SUCCESS; + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ChangePartMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ChangePartMechanic.java new file mode 100644 index 0000000..f476b19 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ChangePartMechanic.java @@ -0,0 +1,99 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; + +@MythicMechanic( + name = "changepart", + aliases = {} +) +public class ChangePartMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderString nModelId; + private final PlaceholderString nPartId; + + public ChangePartMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, null, new String[0]); + this.nModelId = mlc.getPlaceholderString(new String[]{"nm", "nmid", "newmodel", "newmodelid"}, null, new String[0]); + this.nPartId = mlc.getPlaceholderString(new String[]{"np", "npid", "newpart", "newpartid"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + String nModelId = MythicUtils.getOrNullLowercase(this.nModelId, meta, target); + String nPartId = MythicUtils.getOrNullLowercase(this.nPartId, meta, target); + if (modelId != null && partId != null && nModelId != null && nPartId != null) { + model.getModel(modelId).flatMap(activeModel -> activeModel.getBone(partId)).ifPresent(bone -> { + if (bone.isRenderer()) { + ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(nModelId); + if (blueprint != null) { + BlueprintBone blueprintBone = blueprint.getFlatMap().get(nPartId); + if (blueprintBone != null && blueprintBone.isRenderer()) { + bone.setModelScale(blueprintBone.getScale()); + bone.setModel(blueprintBone); + } + } + } + }); + return SkillResult.SUCCESS; + } else { + return SkillResult.INVALID_CONFIG; + } + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta); + String nModelId = MythicUtils.getOrNullLowercase(this.nModelId, meta); + String nPartId = MythicUtils.getOrNullLowercase(this.nPartId, meta); + if (modelId != null && partId != null && nModelId != null && nPartId != null) { + model.getModel(modelId).flatMap(activeModel -> activeModel.getBone(partId)).ifPresent(bone -> { + if (bone.isRenderer()) { + ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(nModelId); + if (blueprint != null) { + BlueprintBone blueprintBone = blueprint.getFlatMap().get(nPartId); + if (blueprintBone != null && blueprintBone.isRenderer()) { + bone.setModelScale(blueprintBone.getScale()); + bone.setModel(blueprintBone); + } + } + } + }); + return SkillResult.SUCCESS; + } else { + return SkillResult.INVALID_CONFIG; + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/CyclePartsMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/CyclePartsMechanic.java new file mode 100644 index 0000000..edd5f44 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/CyclePartsMechanic.java @@ -0,0 +1,112 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.utils.scheduling.PlatformTask; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.bukkit.utils.terminable.Terminable; +import java.util.Arrays; +import java.util.List; + +@MythicMechanic( + name = "cycleparts", + aliases = {} +) +public class CyclePartsMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderString nModelId; + private final List cycledParts = Lists.newArrayList(); + private final int startingFrame = 0; + private final int interval; + private final int duration; + + public CyclePartsMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, null, new String[0]); + this.nModelId = mlc.getPlaceholderString(new String[]{"nm", "nmid", "newmodel", "newmodelid"}, null, new String[0]); + String nPartId = mlc.getString(new String[]{"np", "npid", "newpart", "newpartid", "newparts", "cycledparts"}, "", new String[0]); + this.cycledParts.addAll(Arrays.asList(nPartId.split(","))); + this.interval = mlc.getInteger(new String[]{"interval", "i"}, 1); + this.duration = mlc.getInteger(new String[]{"duration", "d"}, this.cycledParts.size() - 1); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + String nModelId = MythicUtils.getOrNullLowercase(this.nModelId, meta, target); + model.getModel(modelId).flatMap(activeModel -> activeModel.getBone(partId)).ifPresent(bone -> { + if (bone.isRenderer()) { + ModelBlueprint blueprint = ModelEngineAPI.getBlueprint(nModelId); + if (blueprint != null) { + new CyclePartsMechanic.Animator(meta, target, bone, blueprint); + } + } + }); + return SkillResult.SUCCESS; + } + } + + private class Animator implements Runnable, Terminable { + private final SkillMetadata data; + private final AbstractEntity target; + private final ModelBone bone; + private final ModelBlueprint modelBlueprint; + private final PlatformTask task; + private int frame = 0; + private int iteration = 0; + + public Animator(SkillMetadata data, AbstractEntity target, ModelBone bone, ModelBlueprint modelBlueprint) { + this.data = data; + this.target = target; + this.bone = bone; + this.modelBlueprint = modelBlueprint; + this.task = ModelEngineAPI.getAPI() + .getScheduler() + .scheduleRepeating(ModelEngineAPI.getAPI(), target.getBukkitEntity(), this, 0L, (long)CyclePartsMechanic.this.interval); + } + + @Override + public void run() { + if (this.target.isDead()) { + this.terminate(); + } else if (this.iteration++ > CyclePartsMechanic.this.duration) { + this.terminate(); + } else { + String nextPart = CyclePartsMechanic.this.cycledParts.get(this.frame); + BlueprintBone data = this.modelBlueprint.getFlatMap().get(nextPart); + if (data == null) { + this.terminate(); + } else { + this.bone.setModel(data); + this.bone.setModelScale(data.getScale()); + this.frame = (this.frame + 1) % CyclePartsMechanic.this.cycledParts.size(); + } + } + } + + public void close() { + this.task.cancel(); + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/EnchantMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/EnchantMechanic.java new file mode 100644 index 0000000..484bf2d --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/EnchantMechanic.java @@ -0,0 +1,85 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +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.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; +import java.util.Map.Entry; + +@MythicMechanic( + name = "enchant", + aliases = {} +) +public class EnchantMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final boolean enchant; + private final boolean exactMatch; + private final boolean child; + + public EnchantMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, "", new String[0]); + this.enchant = mlc.getBoolean(new String[]{"en", "enchant"}, true); + this.exactMatch = mlc.getBoolean(new String[]{"em", "exact", "match", "exactmatch"}, true); + this.child = mlc.getBoolean(new String[]{"c", "child"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.enchant(activeModel, partId)); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.enchant(activeModel, partId)); + return SkillResult.SUCCESS; + } + } + + private void enchant(ActiveModel activeModel, String partId) { + if (!partId.isBlank()) { + if (this.exactMatch) { + activeModel.getBone(partId).ifPresent(bone -> MythicUtils.executeBoneChild(this.child, bone, v -> v.setEnchanted(this.enchant))); + } else { + for (Entry entry : activeModel.getBones().entrySet()) { + if (entry.getKey().contains(partId)) { + MythicUtils.executeBoneChild(this.child, entry.getValue(), bone -> bone.setEnchanted(this.enchant)); + } + } + } + } else { + for (ModelBone value : activeModel.getBones().values()) { + value.setEnchanted(this.enchant); + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/GlowMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/GlowMechanic.java new file mode 100644 index 0000000..0674b72 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/GlowMechanic.java @@ -0,0 +1,140 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +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.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.adapters.AbstractPlayer; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.core.skills.SkillAudience; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import org.jetbrains.annotations.Nullable; + +@MythicMechanic( + name = "glow", + aliases = {"glowbone"} +) +public class GlowMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderString color; + private final boolean glowing; + private final boolean exactMatch; + private final boolean child; + private final SkillAudience audience; + + public GlowMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, "", new String[0]); + this.glowing = mlc.getBoolean(new String[]{"g", "glow"}, true); + this.color = mlc.getPlaceholderString(new String[]{"c", "color"}, null, new String[0]); + this.exactMatch = mlc.getBoolean(new String[]{"em", "exact", "match", "exactmatch"}, true); + this.child = mlc.getBoolean(new String[]{"c", "child"}, false); + this.audience = mlc.getAudience("audience", null); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String colorString = MythicUtils.getOrNull(this.color, meta, target); + Integer color; + if (colorString != null) { + if (colorString.startsWith("#")) { + colorString = colorString.substring(1); + } + + color = Integer.parseInt(colorString, 16); + } else { + color = null; + } + + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + Set audienceSet = this.resolveAudience(meta, target); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.glow(activeModel, partId, color, audienceSet)); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String colorString = MythicUtils.getOrNull(this.color, meta); + Integer color; + if (colorString != null) { + if (colorString.startsWith("#")) { + colorString = colorString.substring(1); + } + + color = Integer.parseInt(colorString, 16); + } else { + color = null; + } + + String partId = MythicUtils.getOrNullLowercase(this.partId, meta); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + Set audienceSet = this.resolveAudience(meta, null); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.glow(activeModel, partId, color, audienceSet)); + return SkillResult.SUCCESS; + } + } + + @Nullable + private Set resolveAudience(SkillMetadata meta, @Nullable AbstractEntity target) { + if (this.audience == null) { + return null; + } else { + Set uuids = new HashSet<>(); + + for (AbstractPlayer player : this.audience.get(meta, target)) { + uuids.add(player.getUniqueId()); + } + + return uuids; + } + } + + private void glow(ActiveModel activeModel, String partId, Integer color, @Nullable Set audienceSet) { + if (partId.isBlank()) { + activeModel.setGlowing(this.glowing); + activeModel.setGlowColor(color); + activeModel.setGlowAudience(audienceSet); + } else if (this.exactMatch) { + activeModel.getBone(partId).ifPresent(bone -> MythicUtils.executeBoneChild(this.child, bone, bone1 -> this.setGlow(bone1, color, audienceSet))); + } else { + for (Entry entry : activeModel.getBones().entrySet()) { + if (entry.getKey().contains(partId)) { + MythicUtils.executeBoneChild(this.child, entry.getValue(), bone -> this.setGlow(bone, color, audienceSet)); + } + } + } + } + + private void setGlow(ModelBone bone, Integer color, @Nullable Set audienceSet) { + bone.setGlowing(this.glowing); + bone.setGlowColor(color); + bone.setGlowAudience(audienceSet); + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ModelSkinMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ModelSkinMechanic.java new file mode 100644 index 0000000..3ab10e2 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/ModelSkinMechanic.java @@ -0,0 +1,155 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +import com.destroystokyo.paper.profile.PlayerProfile; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.PlayerLimb; +import com.ticxo.modelengine.api.model.bone.type.UserLimb; +import com.ticxo.modelengine.api.utils.MojangAPI; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.List; +import java.util.UUID; +import org.bukkit.entity.Player; +import org.bukkit.profile.PlayerTextures; +import org.bukkit.profile.PlayerTextures.SkinModel; + +@MythicMechanic( + name = "modelplayerskin", + aliases = {"modelskin"} +) +public class ModelSkinMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderString pbone; + private final PlaceholderString username; + private final PlaceholderString uuid; + private final PlaceholderString skin; + private final Boolean isSlim; + + public ModelSkinMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.pbone = mlc.getPlaceholderString(new String[]{"p", "pbone", "limbs"}, null, new String[0]); + this.uuid = mlc.getPlaceholderString(new String[]{"uuid"}, null, new String[0]); + this.username = mlc.getPlaceholderString(new String[]{"user", "name", "username"}, null, new String[0]); + this.skin = mlc.getPlaceholderString(new String[]{"s", "skin"}, null, new String[0]); + String slim = mlc.getString(new String[]{"slim"}, null, new String[0]); + this.isSlim = slim == null ? null : Boolean.parseBoolean(slim); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + AbstractEntity caster = meta.getCaster().getEntity(); + ModeledEntity model = ModelEngineAPI.getModeledEntity(caster.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String username = MythicUtils.getOrNull(this.username, meta, target); + if (username != null) { + MojangAPI.getUUIDFromUsernamePromise(username) + .thenApplyAsync(MojangAPI::fromUUID) + .thenAcceptAsync(profilex -> this.apply(model, profilex, meta, target)); + return SkillResult.SUCCESS; + } else { + String uuidString = MythicUtils.getOrNull(this.uuid, meta, target); + if (uuidString != null) { + UUID uuid = TMath.parseUUID(uuidString); + MojangAPI.fromUUIDPromise(uuid).thenAcceptAsync(profilex -> this.apply(model, profilex, meta, target)); + return SkillResult.SUCCESS; + } else { + String skin = MythicUtils.getOrNull(this.skin, meta, target); + PlayerProfile profile; + if (skin == null) { + if (!(target.getBukkitEntity() instanceof Player player)) { + return SkillResult.INVALID_TARGET; + } + + profile = player.getPlayerProfile(); + } else { + profile = MojangAPI.fromBase64(skin); + } + + return this.apply(model, profile, meta, target); + } + } + } + } + + public boolean getTargetsCreatives() { + return true; + } + + private SkillResult apply(ModeledEntity model, PlayerProfile profile, SkillMetadata meta, AbstractEntity target) { + PlayerProfile finalProfile = this.forceModel(profile); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + String pbone = MythicUtils.getOrNullLowercase(this.pbone, meta, target); + if (modelId == null && pbone == null) { + for (ActiveModel activeModel : model.getModels().values()) { + for (ModelBone modelBone : activeModel.getBones().values()) { + modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(playerLimb -> ((PlayerLimb)playerLimb).setTexture(finalProfile)); + modelBone.getBoneBehavior(BoneBehaviorTypes.USER_LIMB).ifPresent(playerLimb -> ((UserLimb)playerLimb).setTexture(finalProfile)); + } + } + + return SkillResult.SUCCESS; + } else { + List limbs = pbone == null ? null : List.of(pbone.split(",")); + if (modelId == null) { + for (ActiveModel activeModel : model.getModels().values()) { + for (String limb : limbs) { + activeModel.getBone(limb).ifPresent(modelBone -> { + modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(playerLimb -> ((PlayerLimb)playerLimb).setTexture(finalProfile)); + modelBone.getBoneBehavior(BoneBehaviorTypes.USER_LIMB).ifPresent(playerLimb -> ((UserLimb)playerLimb).setTexture(finalProfile)); + }); + } + } + } else { + model.getModel(modelId).ifPresent(activeModelx -> { + if (limbs == null) { + for (ModelBone modelBone : activeModelx.getBones().values()) { + modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(playerLimb -> ((PlayerLimb)playerLimb).setTexture(finalProfile)); + modelBone.getBoneBehavior(BoneBehaviorTypes.USER_LIMB).ifPresent(playerLimb -> ((UserLimb)playerLimb).setTexture(finalProfile)); + } + } else { + for (String seat : limbs) { + activeModelx.getBone(seat).ifPresent(modelBone -> { + modelBone.getBoneBehavior(BoneBehaviorTypes.PLAYER_LIMB).ifPresent(playerLimb -> ((PlayerLimb)playerLimb).setTexture(finalProfile)); + modelBone.getBoneBehavior(BoneBehaviorTypes.USER_LIMB).ifPresent(playerLimb -> ((UserLimb)playerLimb).setTexture(finalProfile)); + }); + } + } + }); + } + + return SkillResult.SUCCESS; + } + } + + private PlayerProfile forceModel(PlayerProfile profile) { + if (this.isSlim == null) { + return profile; + } else { + PlayerTextures texture = profile.getTextures(); + SkinModel model = this.isSlim ? SkinModel.SLIM : SkinModel.CLASSIC; + if (model != texture.getSkinModel()) { + texture.setSkin(texture.getSkin(), model); + profile.setTextures(texture); + } + + return profile; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/PartVisibilityMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/PartVisibilityMechanic.java new file mode 100644 index 0000000..db77d26 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/PartVisibilityMechanic.java @@ -0,0 +1,79 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +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.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; +import java.util.Map.Entry; + +@MythicMechanic( + name = "partvisibility", + aliases = {"partvis"} +) +public class PartVisibilityMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final boolean visible; + private final boolean exactMatch; + private final boolean child; + + public PartVisibilityMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, "", new String[0]); + this.visible = mlc.getBoolean(new String[]{"v", "visible", "visibility"}, false); + this.exactMatch = mlc.getBoolean(new String[]{"em", "exact", "match", "exactmatch"}, true); + this.child = mlc.getBoolean(new String[]{"c", "ch", "child"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.partVis(activeModel, partId)); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.partVis(activeModel, partId)); + return SkillResult.SUCCESS; + } + } + + private void partVis(ActiveModel activeModel, String partId) { + if (this.exactMatch) { + activeModel.getBone(partId).ifPresent(bonex -> MythicUtils.executeBoneChild(this.child, bonex, bone1 -> bone1.setVisible(this.visible))); + } else { + for (Entry bone : activeModel.getBones().entrySet()) { + if (bone.getKey().contains(partId)) { + MythicUtils.executeBoneChild(this.child, bone.getValue(), bone1 -> bone1.setVisible(this.visible)); + } + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/SegmentMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/SegmentMechanic.java new file mode 100644 index 0000000..cd456cd --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/SegmentMechanic.java @@ -0,0 +1,236 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.Segment; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderBoolean; +import io.lumine.mythic.api.skills.placeholders.PlaceholderFloat; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; +import java.util.Map.Entry; + +@MythicMechanic( + name = "segment", + aliases = {"seg"} +) +public class SegmentMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderBoolean bounded; + private final PlaceholderFloat angleLimit; + private final PlaceholderFloat x; + private final PlaceholderFloat y; + private final PlaceholderFloat z; + private final PlaceholderFloat minX; + private final PlaceholderFloat maxX; + private final PlaceholderFloat minY; + private final PlaceholderFloat maxY; + private final PlaceholderFloat minZ; + private final PlaceholderFloat maxZ; + private final PlaceholderFloat extendRate; + private final PlaceholderFloat elasticity; + private final boolean exactMatch; + + public SegmentMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, "", new String[0]); + this.bounded = mlc.getPlaceholderBoolean(new String[]{"b", "bd", "bounded"}, null); + this.angleLimit = mlc.getPlaceholderFloat(new String[]{"a", "al", "angle", "anglelimit"}, null, new String[0]); + this.x = mlc.getPlaceholderFloat(new String[]{"x"}, null, new String[0]); + this.y = mlc.getPlaceholderFloat(new String[]{"y"}, null, new String[0]); + this.z = mlc.getPlaceholderFloat(new String[]{"z"}, null, new String[0]); + this.minX = mlc.getPlaceholderFloat(new String[]{"minx"}, null, new String[0]); + this.maxX = mlc.getPlaceholderFloat(new String[]{"maxx"}, null, new String[0]); + this.minY = mlc.getPlaceholderFloat(new String[]{"miny"}, null, new String[0]); + this.maxY = mlc.getPlaceholderFloat(new String[]{"maxy"}, null, new String[0]); + this.minZ = mlc.getPlaceholderFloat(new String[]{"minz"}, null, new String[0]); + this.maxZ = mlc.getPlaceholderFloat(new String[]{"maxz"}, null, new String[0]); + this.extendRate = mlc.getPlaceholderFloat(new String[]{"e", "er", "extend", "extendrate"}, null, new String[0]); + this.elasticity = mlc.getPlaceholderFloat(new String[]{"el", "elasticity"}, null, new String[0]); + this.exactMatch = mlc.getBoolean(new String[]{"em", "exact", "match", "exactmatch"}, true); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + Boolean bounded = this.bounded == null ? null : this.bounded.get(meta, target); + Float angleLimit = this.angleLimit == null ? null : this.angleLimit.get(meta, target); + Float x = this.x == null ? angleLimit : this.x.get(meta, target); + Float y = this.y == null ? angleLimit : this.y.get(meta, target); + Float z = this.z == null ? angleLimit : this.z.get(meta, target); + Float minX = this.minX == null ? this.negate(x) : this.minX.get(meta, target); + Float maxX = this.maxX == null ? x : this.maxX.get(meta, target); + Float minY = this.minY == null ? this.negate(y) : this.minY.get(meta, target); + Float maxY = this.maxY == null ? y : this.maxY.get(meta, target); + Float minZ = this.minZ == null ? this.negate(z) : this.minZ.get(meta, target); + Float maxZ = this.maxZ == null ? z : this.maxZ.get(meta, target); + Float extendRate = this.extendRate == null ? null : this.extendRate.get(meta, target); + Float elasticity = this.elasticity == null ? null : this.elasticity.get(meta, target); + MythicUtils.executeOptModelId( + model, modelId, activeModel -> this.segment(activeModel, partId, bounded, minX, maxX, minY, maxY, minZ, maxZ, extendRate, elasticity) + ); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + Boolean bounded = this.bounded == null ? null : this.bounded.get(meta); + Float angleLimit = this.angleLimit == null ? null : this.angleLimit.get(meta); + Float x = this.x == null ? angleLimit : this.x.get(meta); + Float y = this.y == null ? angleLimit : this.y.get(meta); + Float z = this.z == null ? angleLimit : this.z.get(meta); + Float minX = this.minX == null ? this.negate(x) : this.minX.get(meta); + Float maxX = this.maxX == null ? x : this.maxX.get(meta); + Float minY = this.minY == null ? this.negate(y) : this.minY.get(meta); + Float maxY = this.maxY == null ? y : this.maxY.get(meta); + Float minZ = this.minZ == null ? this.negate(z) : this.minZ.get(meta); + Float maxZ = this.maxZ == null ? z : this.maxZ.get(meta); + Float extendRate = this.extendRate == null ? null : this.extendRate.get(meta); + Float elasticity = this.elasticity == null ? null : this.elasticity.get(meta); + MythicUtils.executeOptModelId( + model, modelId, activeModel -> this.segment(activeModel, partId, bounded, minX, maxX, minY, maxY, minZ, maxZ, extendRate, elasticity) + ); + return SkillResult.SUCCESS; + } + } + + private Float negate(Float val) { + return val == null ? null : -val; + } + + private void segment( + ActiveModel activeModel, + String partId, + Boolean bounded, + Float minX, + Float maxX, + Float minY, + Float maxY, + Float minZ, + Float maxZ, + Float extendRate, + Float elasticity + ) { + if (!partId.isBlank()) { + if (this.exactMatch) { + activeModel.getBone(partId).ifPresent(bone -> this.setIfSegment(bone, bounded, minX, maxX, minY, maxY, minZ, maxZ, extendRate, elasticity)); + } else { + for (Entry entry : activeModel.getBones().entrySet()) { + if (entry.getKey().contains(partId)) { + this.setIfSegment(entry.getValue(), bounded, minX, maxX, minY, maxY, minZ, maxZ, extendRate, elasticity); + } + } + } + } else { + for (Entry entryx : activeModel.getBones().entrySet()) { + this.setIfSegment(entryx.getValue(), bounded, minX, maxX, minY, maxY, minZ, maxZ, extendRate, elasticity); + } + } + } + + private void setIfSegment( + ModelBone bone, Boolean bounded, Float minX, Float maxX, Float minY, Float maxY, Float minZ, Float maxZ, Float extendRate, Float elasticity + ) { + bone.getBoneBehavior(BoneBehaviorTypes.SEGMENT).ifPresent(segment -> { + if (bounded != null) { + ((Segment)segment).setBounded(bounded); + } + + if (minX != null) { + ((Segment)segment).setMinX(minX); + } + + if (maxX != null) { + ((Segment)segment).setMaxX(maxX); + } + + if (minY != null) { + ((Segment)segment).setMinY(minY); + } + + if (maxY != null) { + ((Segment)segment).setMaxY(maxY); + } + + if (minZ != null) { + ((Segment)segment).setMinZ(minZ); + } + + if (maxZ != null) { + ((Segment)segment).setMaxZ(maxZ); + } + + if (extendRate != null) { + ((Segment)segment).setAlignRate(extendRate); + } + + if (elasticity != null) { + ((Segment)segment).setElasticity(elasticity); + } + }); + bone.getBoneBehavior(BoneBehaviorTypes.TAIL).ifPresent(segment -> { + if (bounded != null) { + ((Segment)segment).setBounded(bounded); + } + + if (minX != null) { + ((Segment)segment).setMinX(minX); + } + + if (maxX != null) { + ((Segment)segment).setMaxX(maxX); + } + + if (minY != null) { + ((Segment)segment).setMinY(minY); + } + + if (maxY != null) { + ((Segment)segment).setMaxY(maxY); + } + + if (minZ != null) { + ((Segment)segment).setMinZ(minZ); + } + + if (maxZ != null) { + ((Segment)segment).setMaxZ(maxZ); + } + + if (extendRate != null) { + ((Segment)segment).setAlignRate(extendRate); + } + + if (elasticity != null) { + ((Segment)segment).setElasticity(elasticity); + } + }); + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/TintMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/TintMechanic.java new file mode 100644 index 0000000..9bd54a9 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/bone/TintMechanic.java @@ -0,0 +1,108 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.bone; + +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.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; +import java.util.Map.Entry; +import org.bukkit.Color; + +@MythicMechanic( + name = "tint", + aliases = {"color"} +) +public class TintMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderString color; + private final boolean damageTint; + private final boolean exactMatch; + private final boolean child; + + public TintMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, "", new String[0]); + this.damageTint = mlc.getBoolean(new String[]{"d", "dmg", "damage", "damagetint"}, false); + this.color = mlc.getPlaceholderString(new String[]{"c", "color"}, this.damageTint ? "FF6666" : "FFFFFF", new String[0]); + this.exactMatch = mlc.getBoolean(new String[]{"em", "exact", "match", "exactmatch"}, true); + this.child = mlc.getBoolean(new String[]{"c", "child"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String colorString = MythicUtils.getOrNull(this.color, meta, target); + if (colorString.startsWith("#")) { + colorString = colorString.substring(1); + } + + Color color = Color.fromRGB(Integer.parseInt(colorString, 16)); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.color(activeModel, partId, color)); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String colorString = MythicUtils.getOrNull(this.color, meta); + if (colorString.startsWith("#")) { + colorString = colorString.substring(1); + } + + Color color = Color.fromRGB(Integer.parseInt(colorString, 16)); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.color(activeModel, partId, color)); + return SkillResult.SUCCESS; + } + } + + private void color(ActiveModel activeModel, String partId, Color color) { + if (partId.isBlank()) { + if (this.damageTint) { + activeModel.setDamageTint(color); + } else { + activeModel.setDefaultTint(color); + } + } else if (this.exactMatch) { + activeModel.getBone(partId).ifPresent(bone -> MythicUtils.executeBoneChild(this.child, bone, v -> this.setColor(v, color))); + } else { + for (Entry entry : activeModel.getBones().entrySet()) { + if (entry.getKey().contains(partId)) { + MythicUtils.executeBoneChild(this.child, entry.getValue(), bone -> this.setColor(bone, color)); + } + } + } + } + + private void setColor(ModelBone bone, Color color) { + if (this.damageTint) { + bone.setDamageTint(color); + } else { + bone.setDefaultTint(color); + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/JumpMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/JumpMechanic.java new file mode 100644 index 0000000..063c90e --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/JumpMechanic.java @@ -0,0 +1,32 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; + +@MythicMechanic( + name = "jump", + aliases = {} +) +public class JumpMechanic implements ITargetedEntitySkill { + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + if (meta.getMetadata("meg:move_controller").orElseGet(() -> { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + return model == null ? null : model.getBase().getMoveController(); + }) instanceof MoveController moveController) { + moveController.jump(); + } + + return SkillResult.SUCCESS; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/MoveMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/MoveMechanic.java new file mode 100644 index 0000000..9cb6675 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/MoveMechanic.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; + +@MythicMechanic( + name = "move", + aliases = {} +) +public class MoveMechanic implements ITargetedEntitySkill { + private final PlaceholderDouble x; + private final PlaceholderDouble y; + private final PlaceholderDouble z; + private final PlaceholderDouble speedModifier; + private final boolean global; + private final boolean queue; + + public MoveMechanic(MythicLineConfig mlc) { + this.x = mlc.getPlaceholderDouble(new String[]{"side", "x"}, "0", new String[0]); + this.y = mlc.getPlaceholderDouble(new String[]{"up", "y"}, "0", new String[0]); + this.z = mlc.getPlaceholderDouble(new String[]{"front", "z"}, "0", new String[0]); + this.speedModifier = mlc.getPlaceholderDouble(new String[]{"speed"}, "1", new String[0]); + this.global = mlc.getBoolean(new String[]{"global", "g"}, false); + this.queue = mlc.getBoolean(new String[]{"queue", "q"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + if (meta.getMetadata("meg:move_controller").orElseGet(() -> { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + return model == null ? null : model.getBase().getMoveController(); + }) instanceof MoveController moveController) { + float x = (float)this.x.get(meta, target); + float y = (float)this.y.get(meta, target); + float z = (float)this.z.get(meta, target); + float speed = (float)this.speedModifier.get(meta, target); + if (this.global) { + if (this.queue) { + moveController.queuePostTick(() -> moveController.globalMove(x, y, z, speed)); + } else { + moveController.globalMove(x, y, z, speed); + } + } else if (this.queue) { + moveController.queuePostTick(() -> moveController.move(x, y, z, speed)); + } else { + moveController.move(x, y, z, speed); + } + } + + return SkillResult.SUCCESS; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/NoFallMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/NoFallMechanic.java new file mode 100644 index 0000000..f945bcf --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/NoFallMechanic.java @@ -0,0 +1,32 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; + +@MythicMechanic( + name = "nofall", + aliases = {"cancelfall", "cancelfalldamage"} +) +public class NoFallMechanic implements ITargetedEntitySkill { + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + if (meta.getMetadata("meg:move_controller").orElseGet(() -> { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + return model == null ? null : model.getBase().getMoveController(); + }) instanceof MoveController moveController) { + moveController.nullifyFallDistance(); + } + + return SkillResult.SUCCESS; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/SyncYawMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/SyncYawMechanic.java new file mode 100644 index 0000000..6727264 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/controller/SyncYawMechanic.java @@ -0,0 +1,61 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import java.util.Locale; +import org.bukkit.entity.Entity; + +@MythicMechanic( + name = "syncyaw", + aliases = {} +) +public class SyncYawMechanic implements ITargetedEntitySkill { + private final String target; + private final String body; + + public SyncYawMechanic(MythicLineConfig mlc) { + this.target = mlc.getString(new String[]{"target", "t", "to"}, "yaw", new String[0]); + this.body = mlc.getString(new String[]{"body", "b", "src", "from"}, "head", new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Entity entity = target.getBukkitEntity(); + EntityHandler handler = ModelEngineAPI.getEntityHandler(); + String var6 = this.body.toLowerCase(Locale.ENGLISH); + + float yaw = switch (var6) { + case "yaw" -> handler.getYRot(entity); + case "body", "true" -> handler.getYBodyRot(entity); + default -> handler.getYHeadRot(entity); + }; + var6 = this.target.toLowerCase(Locale.ENGLISH); + switch (var6) { + case "yaw": + handler.setYRot(entity, yaw); + break; + case "body": + handler.setYBodyRot(entity, yaw); + break; + case "head": + handler.setYHeadRot(entity, yaw); + break; + case "all": + handler.setYRot(entity, yaw); + handler.setYBodyRot(entity, yaw); + handler.setYHeadRot(entity, yaw); + } + + return SkillResult.SUCCESS; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/disguise/DisguiseMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/disguise/DisguiseMechanic.java new file mode 100644 index 0000000..4a8aa4c --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/disguise/DisguiseMechanic.java @@ -0,0 +1,70 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.disguise; + +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.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import org.bukkit.entity.Player; + +@MythicMechanic( + name = "disguise", + aliases = {"modeldisguise"} +) +public class DisguiseMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final boolean viewSelf; + + public DisguiseMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.viewSelf = mlc.getBoolean(new String[]{"s", "see", "seeself"}, true); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + if (ServerInfo.scheduleOnRegion(target.getBukkitEntity(), () -> this.castAtEntity(meta, target))) { + return SkillResult.SUCCESS; + } else if (!target.isPlayer()) { + return SkillResult.INVALID_TARGET; + } else { + Player player = (Player)target.getBukkitEntity(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + ModelBlueprint blueprint = MythicUtils.getBlueprintOrNull(modelId); + if (blueprint == null) { + return SkillResult.INVALID_CONFIG; + } else { + ModeledEntity modeledEntity = ModelEngineAPI.getOrCreateModeledEntity(player); + modeledEntity.getBase().getBodyRotationController().setPlayerMode(true); + modeledEntity.setBaseEntityVisible(false); + if (modeledEntity.getBase().getData() instanceof BukkitEntityData data && this.viewSelf) { + data.getTracked().addForcedPairing(player.getUniqueId()); + } + + ModelEngineAPI.getEntityHandler().setForcedInvisible(player, true); + if (modeledEntity.getModel(modelId).isEmpty()) { + ActiveModel activeModel = ModelEngineAPI.createActiveModel(blueprint); + modeledEntity.addModel(activeModel, false).ifPresent(ActiveModel::destroy); + } + + return SkillResult.SUCCESS; + } + } + } + + public boolean getTargetsCreatives() { + return true; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/disguise/UndisguiseMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/disguise/UndisguiseMechanic.java new file mode 100644 index 0000000..d88eb35 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/disguise/UndisguiseMechanic.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.disguise; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import org.bukkit.entity.Player; + +@MythicMechanic( + name = "undisguise", + aliases = {"modelundisguise"} +) +public class UndisguiseMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + + public UndisguiseMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + if (ServerInfo.scheduleOnRegion(target.getBukkitEntity(), () -> this.castAtEntity(meta, target))) { + return SkillResult.SUCCESS; + } else if (!target.isPlayer()) { + return SkillResult.INVALID_TARGET; + } else { + Player player = (Player)target.getBukkitEntity(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(player); + if (modeledEntity != null) { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + if (modelId == null) { + modeledEntity.setBaseEntityVisible(true); + modeledEntity.markRemoved(); + ModelEngineAPI.getEntityHandler().setForcedInvisible(player, false); + } else { + modeledEntity.removeModel(modelId).ifPresent(ActiveModel::destroy); + if (modeledEntity.getModels().isEmpty()) { + modeledEntity.setBaseEntityVisible(true); + modeledEntity.markRemoved(); + ModelEngineAPI.getEntityHandler().setForcedInvisible(player, false); + } + } + } + + return SkillResult.SUCCESS; + } + } + + public boolean getTargetsCreatives() { + return true; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/BodyRotationMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/BodyRotationMechanic.java new file mode 100644 index 0000000..d1e1df4 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/BodyRotationMechanic.java @@ -0,0 +1,94 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.entity; + +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderFloat; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import java.util.Optional; + +@MythicMechanic( + name = "bodyrotation", + aliases = {"bodyclamp"} +) +public class BodyRotationMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final MythicLineConfig config; + + public BodyRotationMechanic(MythicLineConfig mlc) { + this.config = mlc; + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + BodyRotationController controller = model.getBase().getBodyRotationController(); + boolean headUneven = this.config.getBoolean(new String[]{"hu", "head", "headuneven"}, controller.isHeadClampUneven()); + PlaceholderFloat maxHeadAngle = this.config.getPlaceholderFloat(new String[]{"mh", "mxh", "maxhead"}, controller.getMaxHeadAngle(), new String[0]); + PlaceholderFloat minHeadAngle = this.config.getPlaceholderFloat(new String[]{"mnh", "minhead"}, controller.getMinHeadAngle(), new String[0]); + boolean bodyUneven = this.config.getBoolean(new String[]{"bu", "body", "bodyuneven"}, controller.isBodyClampUneven()); + PlaceholderFloat maxBodyAngle = this.config.getPlaceholderFloat(new String[]{"mb", "mxb", "maxbody"}, controller.getMaxBodyAngle(), new String[0]); + PlaceholderFloat minBodyAngle = this.config.getPlaceholderFloat(new String[]{"mnb", "minbody"}, controller.getMinBodyAngle(), new String[0]); + boolean mode = this.config.getBoolean(new String[]{"m", "mode", "player", "playermode"}, controller.isPlayerMode()); + PlaceholderFloat stableAngle = this.config.getPlaceholderFloat(new String[]{"s", "stable"}, controller.getStableAngle(), new String[0]); + PlaceholderInt rotationDelay = this.config.getPlaceholderInteger(new String[]{"rde", "rdelay"}, controller.getRotationDelay(), new String[0]); + PlaceholderInt rotationDuration = this.config.getPlaceholderInteger(new String[]{"rdu", "rduration"}, controller.getRotationDuration(), new String[0]); + controller.setHeadClampUneven(headUneven); + controller.setMaxHeadAngle(maxHeadAngle.get(meta, target)); + controller.setMinHeadAngle(minHeadAngle.get(meta, target)); + controller.setBodyClampUneven(bodyUneven); + controller.setMaxBodyAngle(maxBodyAngle.get(meta, target)); + controller.setMinBodyAngle(minBodyAngle.get(meta, target)); + controller.setPlayerMode(mode); + controller.setStableAngle(stableAngle.get(meta, target)); + controller.setRotationDelay(rotationDelay.get(meta, target)); + controller.setRotationDuration(rotationDuration.get(meta, target)); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + BodyRotationController controller = model.getBase().getBodyRotationController(); + boolean headUneven = this.config.getBoolean(new String[]{"hu", "head", "headuneven"}, controller.isHeadClampUneven()); + PlaceholderFloat maxHeadAngle = this.config.getPlaceholderFloat(new String[]{"mh", "mxh", "maxhead"}, controller.getMaxHeadAngle(), new String[0]); + PlaceholderFloat minHeadAngle = this.config.getPlaceholderFloat(new String[]{"mnh", "minhead"}, controller.getMinHeadAngle(), new String[0]); + boolean bodyUneven = this.config.getBoolean(new String[]{"bu", "body", "bodyuneven"}, controller.isBodyClampUneven()); + PlaceholderFloat maxBodyAngle = this.config.getPlaceholderFloat(new String[]{"mb", "mxb", "maxbody"}, controller.getMaxBodyAngle(), new String[0]); + PlaceholderFloat minBodyAngle = this.config.getPlaceholderFloat(new String[]{"mnb", "minbody"}, controller.getMinBodyAngle(), new String[0]); + boolean mode = this.config.getBoolean(new String[]{"m", "mode", "player", "playermode"}, controller.isPlayerMode()); + PlaceholderFloat stableAngle = this.config.getPlaceholderFloat(new String[]{"s", "stable"}, controller.getStableAngle(), new String[0]); + PlaceholderInt rotationDelay = this.config.getPlaceholderInteger(new String[]{"rde", "rdelay"}, controller.getRotationDelay(), new String[0]); + PlaceholderInt rotationDuration = this.config.getPlaceholderInteger(new String[]{"rdu", "rduration"}, controller.getRotationDuration(), new String[0]); + controller.setHeadClampUneven(headUneven); + controller.setMaxHeadAngle(maxHeadAngle.get(meta)); + controller.setMinHeadAngle(minHeadAngle.get(meta)); + controller.setBodyClampUneven(bodyUneven); + controller.setMaxBodyAngle(maxBodyAngle.get(meta)); + controller.setMinBodyAngle(minBodyAngle.get(meta)); + controller.setPlayerMode(mode); + controller.setStableAngle(stableAngle.get(meta)); + controller.setRotationDelay(rotationDelay.get(meta)); + controller.setRotationDuration(rotationDuration.get(meta)); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/ConfigureCullMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/ConfigureCullMechanic.java new file mode 100644 index 0000000..45858e7 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/ConfigureCullMechanic.java @@ -0,0 +1,127 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.entity; + +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; +import java.util.function.Function; + +@MythicMechanic( + name = "cullconfig", + aliases = {"cull"} +) +public class ConfigureCullMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final MythicLineConfig config; + + public ConfigureCullMechanic(MythicLineConfig mlc) { + this.config = mlc; + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + IEntityData data = model.getBase().getData(); + Integer cullInterval = this.getOrDefault(meta, target, Integer::parseInt, data.getCullInterval(), "ci", "cullinterval"); + Boolean verticalCull = this.getOrDefault(meta, target, Boolean::parseBoolean, data.getVerticalCull(), "vc", "verticalcull"); + Double verticalCullDistance = this.getOrDefault(meta, target, Double::parseDouble, data.getVerticalCullDistance(), "vcd", "verticalculldistance"); + CullType verticalCullType = this.getOrDefault(meta, target, CullType::get, data.getVerticalCullType(), "vct", "verticalculltype"); + Boolean backCull = this.getOrDefault(meta, target, Boolean::parseBoolean, data.getBackCull(), "bkc", "backcull"); + Double backCullAngle = this.getOrDefault(meta, target, val -> { + double degree = Double.parseDouble(val); + return Math.cos(TMath.clamp(degree, 0.0, 360.0) * 0.5 * (float) (Math.PI / 180.0)); + }, data.getBackCullAngle(), "bkca", "backcullangle"); + Double backCullIgnoreRadius = this.getOrDefault(meta, target, Double::parseDouble, data.getBackCullIgnoreRadius(), "bkcr", "backcullignoreradius"); + CullType backCullType = this.getOrDefault(meta, target, CullType::get, data.getBackCullType(), "bkct", "backculltype"); + Boolean blockedCull = this.getOrDefault(meta, target, Boolean::parseBoolean, data.getBlockedCull(), "blc", "blockedcull"); + Double blockedCullIgnoreRadius = this.getOrDefault( + meta, target, Double::parseDouble, data.getBlockedCullIgnoreRadius(), "blcr", "blockedcullignoreradius" + ); + CullType blockedCullType = this.getOrDefault(meta, target, CullType::get, data.getBlockedCullType(), "blct", "blockedculltype"); + data.setCullInterval(cullInterval); + data.setVerticalCull(verticalCull); + data.setVerticalCullDistance(verticalCullDistance); + data.setVerticalCullType(verticalCullType); + data.setBackCull(backCull); + data.setBackCullAngle(backCullAngle); + data.setBackCullIgnoreRadius(backCullIgnoreRadius); + data.setBackCullType(backCullType); + data.setBlockedCull(blockedCull); + data.setBlockedCullIgnoreRadius(blockedCullIgnoreRadius); + data.setBlockedCullType(blockedCullType); + Boolean animationLod = this.getOrDefault(meta, target, Boolean::parseBoolean, model.getAnimationLodHandler().getEnabled(), "alod", "animationlod"); + model.getAnimationLodHandler().setEnabled(animationLod); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + IEntityData data = model.getBase().getData(); + Integer cullInterval = this.getOrDefault(meta, null, Integer::parseInt, data.getCullInterval(), "ci", "cullinterval"); + Boolean verticalCull = this.getOrDefault(meta, null, Boolean::parseBoolean, data.getVerticalCull(), "vc", "verticalcull"); + Double verticalCullDistance = this.getOrDefault(meta, null, Double::parseDouble, data.getVerticalCullDistance(), "vcd", "verticalculldistance"); + CullType verticalCullType = this.getOrDefault(meta, null, CullType::get, data.getVerticalCullType(), "vct", "verticalculltype"); + Boolean backCull = this.getOrDefault(meta, null, Boolean::parseBoolean, data.getBackCull(), "bkc", "backcull"); + Double backCullAngle = this.getOrDefault(meta, null, val -> { + double degree = Double.parseDouble(val); + return Math.cos(TMath.clamp(degree, 0.0, 360.0) * 0.5 * (float) (Math.PI / 180.0)); + }, data.getBackCullAngle(), "bkca", "backcullangle"); + Double backCullIgnoreRadius = this.getOrDefault(meta, null, Double::parseDouble, data.getBackCullIgnoreRadius(), "bkcr", "backcullignoreradius"); + CullType backCullType = this.getOrDefault(meta, null, CullType::get, data.getBackCullType(), "bkct", "backculltype"); + Boolean blockedCull = this.getOrDefault(meta, null, Boolean::parseBoolean, data.getBlockedCull(), "blc", "blockedcull"); + Double blockedCullIgnoreRadius = this.getOrDefault( + meta, null, Double::parseDouble, data.getBlockedCullIgnoreRadius(), "blcr", "blockedcullignoreradius" + ); + CullType blockedCullType = this.getOrDefault(meta, null, CullType::get, data.getBlockedCullType(), "blct", "blockedculltype"); + data.setCullInterval(cullInterval); + data.setVerticalCull(verticalCull); + data.setVerticalCullDistance(verticalCullDistance); + data.setVerticalCullType(verticalCullType); + data.setBackCull(backCull); + data.setBackCullAngle(backCullAngle); + data.setBackCullIgnoreRadius(backCullIgnoreRadius); + data.setBackCullType(backCullType); + data.setBlockedCull(blockedCull); + data.setBlockedCullIgnoreRadius(blockedCullIgnoreRadius); + data.setBlockedCullType(blockedCullType); + Boolean animationLod = this.getOrDefault(meta, null, Boolean::parseBoolean, model.getAnimationLodHandler().getEnabled(), "alod", "animationlod"); + model.getAnimationLodHandler().setEnabled(animationLod); + return SkillResult.SUCCESS; + } + } + + private T getOrDefault(SkillMetadata meta, AbstractEntity target, Function function, T def, String... alias) { + PlaceholderString placeholder = this.config.getPlaceholderString(alias, null, new String[0]); + if (placeholder != null && placeholder.isPresent()) { + try { + return function.apply(placeholder.get(meta, target)); + } catch (Exception var8) { + return def; + } + } else { + return def; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/ModelMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/ModelMechanic.java new file mode 100644 index 0000000..f44a8d8 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/ModelMechanic.java @@ -0,0 +1,187 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.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.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.operation.ModelOperation; +import com.ticxo.modelengine.api.model.operation.OperationResult; +import com.ticxo.modelengine.api.model.operation.OperationType; +import com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderBoolean; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.bukkit.BukkitAdapter; +import org.bukkit.entity.Player; + +@MythicMechanic( + name = "model", + aliases = {} +) +public class ModelMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderBoolean hitbox; + private final PlaceholderBoolean remove; + private final PlaceholderBoolean killOwner; + private final PlaceholderString invisible; + private final PlaceholderBoolean doDamageTint; + private final PlaceholderString nametag; + private final PlaceholderBoolean canDrive; + private final PlaceholderBoolean canRide; + private final PlaceholderBoolean lockPitch; + private final PlaceholderBoolean lockYaw; + private final PlaceholderDouble stepHeight; + private final PlaceholderInt viewRadius; + private final PlaceholderDouble viewRange; + private final PlaceholderDouble scale; + private final PlaceholderDouble hitboxScale; + private final PlaceholderBoolean useStateMachine; + private final PlaceholderBoolean invisUpdate; + private final PlaceholderBoolean initRenderer; + private final PlaceholderBoolean showHitbox; + private final PlaceholderBoolean showShadow; + private final PlaceholderBoolean syncBodyYaw; + private final PlaceholderBoolean shouldSave; + private final PlaceholderBoolean viewSelf; + private final PlaceholderBoolean shouldTrack; + private final PlaceholderBoolean pivotOverride; + private final PlaceholderBoolean cameraPivot; + private final PlaceholderBoolean renderFire; + private final PlaceholderBoolean forceFire; + private final PlaceholderString rootBone; + + public ModelMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.hitbox = mlc.getPlaceholderBoolean(new String[]{"h", "hitbox"}, true); + this.remove = mlc.getPlaceholderBoolean(new String[]{"r", "remove"}, false); + this.killOwner = mlc.getPlaceholderBoolean(new String[]{"ko", "killowner"}, false); + this.invisible = mlc.getPlaceholderString(new String[]{"i", "invis", "invisible"}, null, new String[0]); + this.doDamageTint = mlc.getPlaceholderBoolean(new String[]{"d", "tint", "damagetint"}, true); + this.nametag = mlc.getPlaceholderString(new String[]{"n", "name", "nametag"}, null, new String[0]); + this.canDrive = mlc.getPlaceholderBoolean(new String[]{"drive"}, false); + this.canRide = mlc.getPlaceholderBoolean(new String[]{"ride"}, false); + this.lockPitch = mlc.getPlaceholderBoolean(new String[]{"lp", "lpitch", "lockpitch"}, false); + this.lockYaw = mlc.getPlaceholderBoolean(new String[]{"ly", "lyaw", "lockyaw"}, false); + this.stepHeight = mlc.getPlaceholderDouble(new String[]{"s", "step"}, (String)null, new String[0]); + this.viewRadius = mlc.getPlaceholderInteger(new String[]{"rad", "radius"}, 0, new String[0]); + this.viewRange = mlc.getPlaceholderDouble(new String[]{"vr", "viewrange"}, "4096", new String[0]); + this.scale = mlc.getPlaceholderDouble(new String[]{"scale"}, "1", new String[0]); + this.hitboxScale = mlc.getPlaceholderDouble(new String[]{"hitboxscale"}, this.scale, new String[0]); + this.useStateMachine = mlc.getPlaceholderBoolean(new String[]{"usm", "state", "statemachine", "usestatemachine"}, false); + this.invisUpdate = mlc.getPlaceholderBoolean(new String[]{"iu", "invisupdate"}, false); + this.initRenderer = mlc.getPlaceholderBoolean(new String[]{"init", "initrender"}, true); + this.showHitbox = mlc.getPlaceholderBoolean(new String[]{"showhitbox"}, true); + this.showShadow = mlc.getPlaceholderBoolean(new String[]{"showshadow"}, true); + this.syncBodyYaw = mlc.getPlaceholderBoolean(new String[]{"syncbody"}, true); + this.shouldSave = mlc.getPlaceholderBoolean(new String[]{"save"}, false); + this.viewSelf = mlc.getPlaceholderBoolean(new String[]{"vs", "see", "seeself"}, true); + this.shouldTrack = mlc.getPlaceholderBoolean(new String[]{"track"}, null); + this.pivotOverride = mlc.getPlaceholderBoolean(new String[]{"pv", "pivot"}, false); + this.cameraPivot = mlc.getPlaceholderBoolean(new String[]{"campivot", "camerapivot"}, false); + this.renderFire = mlc.getPlaceholderBoolean(new String[]{"rf", "renderfire"}, null); + this.forceFire = mlc.getPlaceholderBoolean(new String[]{"ff", "forcefire"}, null); + this.rootBone = mlc.getPlaceholderString(new String[]{"rt", "root", "rootbone"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + return ServerInfo.scheduleOnRegion(BukkitAdapter.adapt(target), () -> this.castAtEntitySync(meta, target)) + ? SkillResult.SUCCESS + : this.castAtEntitySync(meta, target); + } + + private SkillResult castAtEntitySync(SkillMetadata meta, AbstractEntity target) { + return this.remove.get(meta, target) ? this.removeModel(meta, target) : this.addModel(meta, target); + } + + private SkillResult removeModel(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + boolean disguise = target.isPlayer(); + String id = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + if (id == null) { + for (ActiveModel activeModel : model.getModels().values()) { + model.removeModel(activeModel.getBlueprint().getName()).ifPresent(ActiveModel::destroy); + } + } else { + model.removeModel(id).ifPresent(ActiveModel::destroy); + } + + if (this.killOwner.get(meta, target)) { + target.remove(); + return SkillResult.SUCCESS; + } else { + if (model.getModels().isEmpty()) { + model.setBaseEntityVisible(true); + ModelEngineAPI.removeModeledEntity(target.getUniqueId()); + ModelEngineAPI.getEntityHandler().setForcedInvisible(BukkitAdapter.adapt(target), false); + if (disguise) { + Player player = BukkitAdapter.adapt(target.asPlayer()); + if (model.getBase().getData() instanceof BukkitEntityData data) { + data.getTracked().setBaseRange(data.getTracked().getInitialBaseRange()); + data.getTracked().setPlayerPredicate(TrackedEntity.DEFAULT_PREDICATE); + } + } + } else { + String strInvis = MythicUtils.getOrNullLowercase(this.invisible, meta, target); + if (strInvis != null) { + model.setBaseEntityVisible(Boolean.parseBoolean(strInvis)); + } + } + + return SkillResult.SUCCESS; + } + } + } + + private SkillResult addModel(SkillMetadata meta, AbstractEntity target) { + String strInvis = MythicUtils.getOrNullLowercase(this.invisible, meta, target); + OperationResult result = ModelOperation.builder() + .bukkitEntity(BukkitAdapter.adapt(target)) + .modelId(MythicUtils.getOrNullLowercase(this.modelId, meta, target)) + .overrideHitbox(this.hitbox.get(meta, target)) + .stepHeight(this.stepHeight == null ? null : this.stepHeight.get(meta, target)) + .viewRadius(this.viewRadius.get(meta, target)) + .viewRange((float)this.viewRange.get(meta, target)) + .scale(this.scale.get(meta, target)) + .hitboxScale(this.hitboxScale.get(meta, target)) + .shouldSave(this.shouldSave.get(meta, target)) + .baseInvisible(strInvis == null || Boolean.parseBoolean(strInvis)) + .doDamageTint(this.doDamageTint.get(meta, target)) + .lockPitch(this.lockPitch.get(meta, target)) + .lockYaw(this.lockYaw.get(meta, target)) + .invisibleUpdate(this.invisUpdate.get(meta, target)) + .initializeRenderer(this.initRenderer.get(meta, target)) + .syncBodyYaw(this.syncBodyYaw.get(meta, target)) + .useStateMachine(this.useStateMachine.get(meta, target)) + .useBaseAsPivot(this.pivotOverride.get(meta, target)) + .cameraPivot(this.cameraPivot.get(meta, target)) + .showHitbox(this.showHitbox.get(meta, target)) + .showShadow(this.showShadow.get(meta, target)) + .drivable(this.canDrive.get(meta, target)) + .rideable(this.canRide.get(meta, target)) + .nametagBone(MythicUtils.getOrNullLowercase(this.nametag, meta, target)) + .rootBone(MythicUtils.getOrNullLowercase(this.rootBone, meta, target)) + .renderFire(this.renderFire == null ? null : this.renderFire.get(meta, target)) + .forceFire(this.forceFire == null ? null : this.forceFire.get(meta, target)) + .viewSelf(this.viewSelf.get(meta, target)) + .playerPredicate(this.shouldTrack == null ? null : (this.shouldTrack.get(meta, target) ? TrackedEntity.DEFAULT_PREDICATE : player -> false)) + .operate(OperationType.ADD_MODEL); + return result.isSuccessful() ? SkillResult.SUCCESS : SkillResult.ERROR; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/PairModelMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/PairModelMechanic.java new file mode 100644 index 0000000..9cb0ee1 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/PairModelMechanic.java @@ -0,0 +1,60 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.entity; + +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import java.util.Optional; +import org.bukkit.entity.Player; + +@MythicMechanic( + name = "pairmodel", + aliases = {} +) +public class PairModelMechanic implements ITargetedEntitySkill { + private final boolean hidden; + private final boolean remove; + + public PairModelMechanic(MythicLineConfig mlc) { + this.hidden = mlc.getBoolean(new String[]{"h", "hidden"}, false); + this.remove = mlc.getBoolean(new String[]{"r", "remove"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, meta.getCaster().getEntity().getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + if (model.getBase().getData() instanceof BukkitEntityData data && target.getBukkitEntity() instanceof Player player) { + if (this.hidden) { + if (this.remove) { + data.getTracked().removeForcedHidden(player.getUniqueId()); + } else { + data.getTracked().addForcedHidden(player.getUniqueId()); + } + } else if (this.remove) { + data.getTracked().removeForcedPairing(player.getUniqueId()); + } else { + data.getTracked().addForcedPairing(player.getUniqueId()); + } + } + + return SkillResult.SUCCESS; + } + } + + public boolean getTargetsCreatives() { + return true; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/PetrifyMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/PetrifyMechanic.java new file mode 100644 index 0000000..eec8f36 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/entity/PetrifyMechanic.java @@ -0,0 +1,40 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; + +@MythicMechanic( + name = "petrify", + aliases = {} +) +public class PetrifyMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + + public PetrifyMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + model.getModel(modelId).ifPresent(activeModel -> activeModel.getModelRenderer().createRealEntities()); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/hitbox/BindHitboxMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/hitbox/BindHitboxMechanic.java new file mode 100644 index 0000000..7e8f0a8 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/hitbox/BindHitboxMechanic.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.adapters.AbstractLocation; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.mobs.MythicMob; +import io.lumine.mythic.api.mobs.entities.SpawnReason; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillCaster; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.bukkit.adapters.BukkitEntityType; +import io.lumine.mythic.core.logging.MythicLogger; +import io.lumine.mythic.core.mobs.ActiveMob; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.joml.Vector3f; + +@MythicMechanic( + name = "bindhitbox", + aliases = {} +) +public class BindHitboxMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final String strType; + private final boolean inheritFaction; + private MythicMob mm; + private BukkitEntityType me; + + public BindHitboxMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, null, new String[0]); + this.strType = mlc.getString(new String[]{"type", "t", "mob", "m"}, "SKELETON", new String[0]); + this.inheritFaction = mlc.getBoolean(new String[]{"inheritfaction", "if"}, true); + this.getPlugin().getSkillManager().queueSecondPass(() -> { + this.mm = (MythicMob)this.getPlugin().getMobManager().getMythicMob(this.strType).orElse(null); + if (this.mm == null) { + this.me = BukkitEntityType.getMythicEntity(this.strType); + if (this.me == null) { + MythicLogger.errorGenericConfig(mlc, "The 'type' attribute must be a valid MythicMob or MythicEntity type."); + } + } + }); + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + model.getModel(modelId).ifPresent(activeModel -> { + String pbone = MythicUtils.getOrNullLowercase(this.partId, meta, target); + if (pbone != null) { + List hitboxes = List.of(pbone.split(",")); + ArrayList subHitboxes = new ArrayList<>(); + + for (String hitboxId : hitboxes) { + Optional maybeBone = activeModel.getBone(hitboxId); + if (!maybeBone.isEmpty()) { + ModelBone bone = maybeBone.get(); + Optional maybeHitbox = bone.getBoneBehavior(BoneBehaviorTypes.SUB_HITBOX); + if (!maybeHitbox.isEmpty()) { + subHitboxes.add((SubHitbox)maybeHitbox.get()); + } + } + } + + this.createBoundEntity(meta.getCaster(), subHitboxes); + } + }); + return SkillResult.SUCCESS; + } + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + private void createBoundEntity(SkillCaster caster, List subHitboxes) { + if (!subHitboxes.isEmpty()) { + AbstractEntity abstractCaster = caster.getEntity(); + Vector3f vec = subHitboxes.get(0).getLocation(); + AbstractLocation l = new AbstractLocation(abstractCaster.getWorld(), vec.x, vec.y, vec.z); + if (this.mm != null) { + ActiveMob ams = this.mm.spawn(l, caster.getLevel(), SpawnReason.SUMMON, entity -> { + for (SubHitbox hitbox : subHitboxes) { + hitbox.addBoundEntity(entity); + } + }); + ams.setParent(caster); + ams.setOwnerUUID(abstractCaster.getUniqueId()); + if (this.inheritFaction && caster instanceof ActiveMob am) { + ams.setFaction(am.getFaction()); + } + } else if (this.me != null) { + this.me.spawn(l, SpawnReason.SUMMON, entity -> { + for (SubHitbox hitbox : subHitboxes) { + hitbox.addBoundEntity(entity); + } + }); + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/hitbox/ConfigureHitboxMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/hitbox/ConfigureHitboxMechanic.java new file mode 100644 index 0000000..1aa0be3 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/hitbox/ConfigureHitboxMechanic.java @@ -0,0 +1,55 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; + +@MythicMechanic( + name = "hitboxconfig", + aliases = {} +) +public class ConfigureHitboxMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderDouble shouldPass; + + public ConfigureHitboxMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, null, new String[0]); + this.shouldPass = mlc.getPlaceholderDouble(new String[]{"pass"}, "1", new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + model.getModel(modelId) + .ifPresent( + activeModel -> { + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + activeModel.getBone(partId) + .flatMap(modelBone -> modelBone.getBoneBehavior(BoneBehaviorTypes.SUB_HITBOX)) + .ifPresent(subHitbox -> ((SubHitbox)subHitbox).setDamageMultiplier((float)this.shouldPass.get(meta, target))); + } + ); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/item/LinkItemBoneMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/item/LinkItemBoneMechanic.java new file mode 100644 index 0000000..841920e --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/item/LinkItemBoneMechanic.java @@ -0,0 +1,70 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.item; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.type.HeldItem; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.core.drops.EquipSlot; +import org.bukkit.entity.LivingEntity; +import org.bukkit.inventory.EquipmentSlot; + +@MythicMechanic( + name = "linkitembone", + aliases = {} +) +public class LinkItemBoneMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderString slot; + + public LinkItemBoneMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"b", "bone", "p", "pid", "part", "partid"}, null, new String[0]); + this.slot = mlc.getPlaceholderString(new String[]{"s", "slot"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + model.getModel(modelId).ifPresent(activeModel -> { + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + activeModel.getBone(partId).ifPresent(modelBone -> modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM).ifPresent(heldItem -> { + String slotString = MythicUtils.getOrNull(this.slot, meta, target); + if (slotString == null) { + ((HeldItem)heldItem).clearItemProvider(); + } else { + EquipmentSlot bukkitSlot = EquipSlot.of(slotString).getBukkitSlot(); + if (bukkitSlot == null) { + ((HeldItem)heldItem).clearItemProvider(); + } else { + if (target.getBukkitEntity() instanceof LivingEntity livingEntity) { + if (livingEntity.getEquipment() == null) { + return; + } + + ((HeldItem)heldItem).setItemProvider(new HeldItem.EquipmentSupplier(livingEntity, bukkitSlot)); + } + } + } + })); + }); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/item/SetItemModelMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/item/SetItemModelMechanic.java new file mode 100644 index 0000000..da16178 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/item/SetItemModelMechanic.java @@ -0,0 +1,137 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.item; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.type.HeldItem; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.adapters.AbstractItemStack; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.bukkit.BukkitAdapter; +import io.lumine.mythic.core.items.MythicItem; +import io.lumine.mythic.core.skills.placeholders.PlaceholderContext; +import io.lumine.mythic.core.skills.variables.types.ItemVariable; +import java.util.Optional; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +@MythicMechanic( + name = "setitemmodel", + aliases = {} +) +public class SetItemModelMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderString strMat; + private final PlaceholderInt data; + private final PlaceholderString color; + private final boolean enchanted; + + public SetItemModelMechanic(MythicLineConfig config) { + this.modelId = config.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = config.getPlaceholderString(new String[]{"b", "bone", "p", "pid", "part", "partid"}, null, new String[0]); + this.strMat = config.getPlaceholderString(new String[]{"i", "item", "mat", "material"}, null, new String[0]); + this.data = config.getPlaceholderInteger(new String[]{"data"}, 0, new String[0]); + this.color = config.getPlaceholderString(new String[]{"color"}, null, new String[0]); + this.enchanted = config.getBoolean(new String[]{"enchant"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + model.getModel(modelId).ifPresent(activeModel -> { + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + activeModel.getBone(partId).ifPresent(modelBone -> modelBone.getBoneBehavior(BoneBehaviorTypes.ITEM).ifPresent(heldItem -> { + ItemStack stack = BukkitAdapter.adapt(this.getItem(meta, target)); + ((HeldItem)heldItem).setItemProvider(new HeldItem.StaticItemStackSupplier(stack)); + })); + }); + return SkillResult.SUCCESS; + } + } + + private AbstractItemStack getItem(SkillMetadata meta, AbstractEntity target) { + AbstractItemStack itemStack = null; + String strMat = MythicUtils.getOrNull(this.strMat, meta, target); + + try { + return ItemVariable.fromStringWithContext(strMat, PlaceholderContext.ofMeta(meta)); + } catch (Exception var15) { + int data = this.data.get(meta, target); + String color = MythicUtils.getOrNull(this.color, meta, target); + boolean isMI = false; + + try { + isMI = true; + if (strMat.contains(":")) { + isMI = false; + String[] mat = strMat.split(":", 2); + String mId = mat[0]; + String pId = mat[1]; + ModelBlueprint blueprint = MythicUtils.getBlueprintOrNull(mId); + if (blueprint == null) { + isMI = true; + } else { + BlueprintBone bone = blueprint.getFlatMap().get(pId); + if (bone == null) { + isMI = true; + } else { + int mData = bone.getDataId(); + if (mData == -1) { + isMI = true; + } else { + itemStack = BukkitAdapter.adapt(bone.getBaseItem().getMaterial()).modelData(mData); + } + } + } + } + + if (isMI) { + Optional maybeMI = this.getPlugin().getItemManager().getItem(strMat); + if (maybeMI.isPresent()) { + itemStack = maybeMI.get().generateItemStack(1); + } else { + Material mat = Material.valueOf(strMat.toUpperCase()); + itemStack = BukkitAdapter.adapt(mat).modelData(data); + } + } + } catch (Exception var14) { + var14.printStackTrace(); + itemStack = BukkitAdapter.adapt(Material.STONE); + } + + if (itemStack == null) { + itemStack = BukkitAdapter.adapt(Material.STONE); + } + + if (!isMI) { + if (color != null) { + itemStack.color(color); + } + + if (this.enchanted) { + itemStack.enchantmentGlow(true); + } + } + + return itemStack; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/leash/LeashMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/leash/LeashMechanic.java new file mode 100644 index 0000000..8bea786 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/leash/LeashMechanic.java @@ -0,0 +1,62 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.leash; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.manager.LeashManager; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; + +@MythicMechanic( + name = "leash", + aliases = {} +) +public class LeashMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderString sourceId; + private final boolean flag; + + public LeashMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.sourceId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, null, new String[0]); + this.flag = mlc.getBoolean(new String[]{"l", "leash"}, true); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + if (ServerInfo.scheduleOnRegion(target.getBukkitEntity(), () -> this.castAtEntity(meta, target))) { + return SkillResult.SUCCESS; + } else { + AbstractEntity caster = meta.getCaster().getEntity(); + ModeledEntity model = ModelEngineAPI.getModeledEntity(caster.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + model.getModel(modelId).ifPresent(activeModel -> activeModel.getLeashManager().ifPresent(leashManager -> { + String sourceId = MythicUtils.getOrNullLowercase(this.sourceId, meta, target); + if (this.flag) { + ((LeashManager)leashManager).connectLeash(target.getBukkitEntity(), sourceId); + } else { + ((LeashManager)leashManager).disconnect(sourceId); + } + })); + return SkillResult.SUCCESS; + } + } + } + + public boolean getTargetsCreatives() { + return true; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/leash/LeashSelfMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/leash/LeashSelfMechanic.java new file mode 100644 index 0000000..69b9206 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/leash/LeashSelfMechanic.java @@ -0,0 +1,50 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.leash; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.manager.LeashManager; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; + +@MythicMechanic( + name = "leashself", + aliases = {} +) +public class LeashSelfMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderString sourceId; + private final PlaceholderString destId; + + public LeashSelfMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.sourceId = mlc.getPlaceholderString(new String[]{"s", "sid", "src", "source", "sourceid"}, null, new String[0]); + this.destId = mlc.getPlaceholderString(new String[]{"d", "did", "dest", "destid"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + AbstractEntity caster = meta.getCaster().getEntity(); + ModeledEntity model = ModelEngineAPI.getModeledEntity(caster.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + model.getModel(modelId).ifPresent(activeModel -> activeModel.getLeashManager().ifPresent(leashManager -> { + String sourceId = MythicUtils.getOrNullLowercase(this.sourceId, meta, target); + String destId = MythicUtils.getOrNullLowercase(this.destId, meta, target); + ((LeashManager)leashManager).connectLeash(destId, sourceId); + })); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/DefaultStateMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/DefaultStateMechanic.java new file mode 100644 index 0000000..3e90042 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/DefaultStateMechanic.java @@ -0,0 +1,86 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.ModelState; +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.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.utils.MiscUtils; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderBoolean; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import it.unimi.dsi.fastutil.Pair; + +@MythicMechanic( + name = "defaultstate", + aliases = {"defaultanimation"} +) +public class DefaultStateMechanic implements ITargetedEntitySkill { + private final MythicLineConfig config; + private final PlaceholderString modelId; + private final PlaceholderString type; + private ModelState stateType; + + public DefaultStateMechanic(MythicLineConfig mlc) { + this.config = mlc; + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.type = mlc.getPlaceholderString(new String[]{"t", "type"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String type = MythicUtils.getOrNull(this.type, meta, target); + if (type == null) { + return SkillResult.INVALID_CONFIG; + } else { + this.stateType = ModelState.get(type); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.configureModel(activeModel, meta, target)); + return SkillResult.SUCCESS; + } + } + } + + private void configureModel(ActiveModel activeModel, SkillMetadata meta, AbstractEntity target) { + AnimationHandler animationHandler = activeModel.getAnimationHandler(); + AnimationHandler.DefaultProperty property = animationHandler.getDefaultProperty(this.stateType); + PlaceholderString statePlaceholder = this.config.getPlaceholderString(new String[]{"s", "state"}, property.getAnimation(), new String[0]); + PlaceholderInt lerpInPlaceholder = this.config.getPlaceholderInteger(new String[]{"li", "lerpin"}, (int)(property.getLerpIn() * 20.0), new String[0]); + PlaceholderInt lerpOutPlaceholder = this.config.getPlaceholderInteger(new String[]{"lo", "lerpout"}, (int)(property.getLerpOut() * 20.0), new String[0]); + PlaceholderDouble speedPlaceholder = this.config.getPlaceholderDouble(new String[]{"sp", "speed"}, property.getSpeed(), new String[0]); + PlaceholderBoolean mergePlaceholder = this.config.getPlaceholderBoolean(new String[]{"mg", "merge"}, property.isMerge()); + Pair statePair = MiscUtils.getAnimationRef(statePlaceholder.get(meta, target)); + PlaceholderString srcId = this.config + .getPlaceholderString(new String[]{"src", "sid", "srcmodel", "srcmodelid"}, (String)statePair.first(), new String[0]); + String state = MiscUtils.createAnimationRef(MythicUtils.getOrNull(srcId, meta, target), (String)statePair.second()); + double lerpIn = lerpInPlaceholder.get(meta, target) * 0.05; + double lerpOut = lerpOutPlaceholder.get(meta, target) * 0.05; + double speed = speedPlaceholder.get(meta, target); + boolean merge = mergePlaceholder.get(meta, target); + animationHandler.setDefaultProperty(new AnimationHandler.DefaultProperty(this.stateType, state, lerpIn, lerpOut, speed, merge)); + if (animationHandler instanceof IPriorityHandler priorityHandler && priorityHandler.isPlayingAnimation(property.getAnimation())) { + priorityHandler.stopAnimation(property.getAnimation()); + priorityHandler.playState(this.stateType); + } else if (animationHandler instanceof IStateMachineHandler stateMachineHandler) { + stateMachineHandler.refreshState(property); + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/LockHeadMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/LockHeadMechanic.java new file mode 100644 index 0000000..258d648 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/LockHeadMechanic.java @@ -0,0 +1,50 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; + +@MythicMechanic( + name = "lockmodelhead", + aliases = {"lockhead"} +) +public class LockHeadMechanic implements ITargetedEntitySkill { + private final MythicLineConfig config; + private final PlaceholderString modelId; + + public LockHeadMechanic(MythicLineConfig mlc) { + this.config = mlc; + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + MythicUtils.executeOptModelId(model, modelId, this::lock); + return SkillResult.SUCCESS; + } + } + + private void lock(ActiveModel activeModel) { + boolean lockPitch = this.config.getBoolean(new String[]{"lp", "lpitch", "lockpitch"}, activeModel.isLockPitch()); + boolean lockYaw = this.config.getBoolean(new String[]{"ly", "lyaw", "lockyaw"}, activeModel.isLockYaw()); + activeModel.setLockPitch(lockPitch); + activeModel.setLockYaw(lockYaw); + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/LockModelRotationMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/LockModelRotationMechanic.java new file mode 100644 index 0000000..1ba074c --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/LockModelRotationMechanic.java @@ -0,0 +1,69 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderBoolean; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; + +@MythicMechanic( + name = "lockmodel", + aliases = {"lockrotation"} +) +public class LockModelRotationMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderBoolean lock; + + public LockModelRotationMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.lock = mlc.getPlaceholderBoolean(new String[]{"l", "lock"}, true); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + boolean lock = this.lock.get(meta, target); + if (modelId != null) { + MythicUtils.executeOptModelId(model, modelId, activeModel -> activeModel.setModelRotationLocked(lock)); + } else { + model.setModelRotationLocked(lock); + } + + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + boolean lock = this.lock.get(meta); + if (modelId != null) { + MythicUtils.executeOptModelId(model, modelId, activeModel -> activeModel.setModelRotationLocked(lock)); + } else { + model.setModelRotationLocked(lock); + } + + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/ModifyStateMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/ModifyStateMechanic.java new file mode 100644 index 0000000..f2f252e --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/ModifyStateMechanic.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.animation.BlueprintAnimation; +import com.ticxo.modelengine.api.animation.handler.AnimationHandler; +import com.ticxo.modelengine.api.animation.handler.IStateMachineHandler; +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.utils.math.Easing; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; + +@MythicMechanic( + name = "modifystate", + aliases = {"modifyanimation", "modstate"} +) +public class ModifyStateMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final MythicLineConfig mlc; + private final PlaceholderString modelId; + private final PlaceholderString state; + private final PlaceholderInt priority; + + public ModifyStateMechanic(MythicLineConfig mlc) { + this.mlc = mlc; + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.state = mlc.getPlaceholderString(new String[]{"s", "state"}, null, new String[0]); + this.priority = mlc.getPlaceholderInteger(new String[]{"p", "pr", "priority"}, 1, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + String state = MythicUtils.getOrNullLowercase(this.state, meta, target); + model.getModel(modelId).ifPresentOrElse(activeModel -> this.configureAnimation(state, activeModel, meta, target), () -> { + for (ActiveModel activeModel : model.getModels().values()) { + this.configureAnimation(state, activeModel, meta, target); + } + }); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + String state = MythicUtils.getOrNullLowercase(this.state, meta); + model.getModel(modelId).ifPresentOrElse(activeModel -> this.configureAnimation(state, activeModel, meta, null), () -> { + for (ActiveModel activeModel : model.getModels().values()) { + this.configureAnimation(state, activeModel, meta, null); + } + }); + return SkillResult.SUCCESS; + } + } + + private void configureAnimation(String state, ActiveModel activeModel, SkillMetadata meta, AbstractEntity target) { + AnimationHandler handler = activeModel.getAnimationHandler(); + IAnimationProperty property; + if (handler instanceof IStateMachineHandler stateMachineHandler) { + int priority = this.priority.get(meta, target); + property = stateMachineHandler.getAnimation(priority, state); + } else { + property = handler.getAnimation(state); + } + + if (property != null) { + PlaceholderDouble speedPlaceholder = this.mlc.getPlaceholderDouble(new String[]{"sp", "speed"}, property.getSpeed(), new String[0]); + PlaceholderInt lerpInPlaceholder = this.mlc.getPlaceholderInteger(new String[]{"li", "lerpin"}, (int)(property.getLerpIn() * 20.0), new String[0]); + PlaceholderInt lerpOutPlaceholder = this.mlc.getPlaceholderInteger(new String[]{"lo", "lerpout"}, (int)(property.getLerpOut() * 20.0), new String[0]); + BlueprintAnimation.LoopMode loopMode = property.getForceLoopMode(); + PlaceholderString loopModePlaceholder = this.mlc + .getPlaceholderString(new String[]{"l", "loop"}, loopMode == null ? null : loopMode.name(), new String[0]); + loopMode = BlueprintAnimation.LoopMode.getOrNull(MythicUtils.getOrNull(loopModePlaceholder, meta, target)); + BlueprintAnimation.OverrideMode override = property.getForceOverride(); + PlaceholderString overridePlaceholder = this.mlc + .getPlaceholderString(new String[]{"ov", "override"}, override == null ? null : override.name(), new String[0]); + override = BlueprintAnimation.OverrideMode.getOrNull(MythicUtils.getOrNull(overridePlaceholder, meta, target)); + Easing curveIn = property.getLerpCurveIn(); + PlaceholderString curveInPlaceholder = this.mlc.getPlaceholderString(new String[]{"lci", "lerpcurvein"}, curveIn.name(), new String[0]); + curveIn = Easing.get(MythicUtils.getOrNull(curveInPlaceholder, meta, target)); + Easing curveOut = property.getLerpCurveOut(); + PlaceholderString curveOutPlaceholder = this.mlc.getPlaceholderString(new String[]{"lco", "lerpcurveout"}, curveOut.name(), new String[0]); + curveOut = Easing.get(MythicUtils.getOrNull(curveOutPlaceholder, meta, target)); + property.setSpeed(speedPlaceholder.get(meta, target)); + property.setLerpIn(lerpInPlaceholder.get(meta, target) * 0.05); + property.setLerpOut(lerpOutPlaceholder.get(meta, target) * 0.05); + property.setForceLoopMode(loopMode); + property.setForceOverride(override); + property.setLerpCurveIn(curveIn); + property.setLerpCurveOut(curveOut); + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RemapModelMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RemapModelMechanic.java new file mode 100644 index 0000000..cd45272 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RemapModelMechanic.java @@ -0,0 +1,147 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; + +@MythicMechanic( + name = "remapmodel", + aliases = {"remap"} +) +public class RemapModelMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString newModelId; + private final PlaceholderString map; + + public RemapModelMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.newModelId = mlc.getPlaceholderString(new String[]{"n", "nid", "newmodel", "newmodelid"}, null, new String[0]); + this.map = mlc.getPlaceholderString(new String[]{"map"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + ActiveModel activeModel = MythicUtils.getActiveModelOrNull(model, modelId); + if (activeModel == null) { + return SkillResult.INVALID_CONFIG; + } else { + String newModelId = MythicUtils.getOrNullLowercase(this.newModelId, meta, target); + ModelBlueprint blueprint = MythicUtils.getBlueprintOrNull(newModelId); + if (blueprint == null) { + return SkillResult.INVALID_CONFIG; + } else { + if (this.map != null) { + String mapId = MythicUtils.getOrNullLowercase(this.map, meta, target); + ModelBlueprint mapBlueprint = MythicUtils.getBlueprintOrNull(mapId); + if (mapBlueprint == null) { + return SkillResult.INVALID_CONFIG; + } + + for (String bone : mapBlueprint.getFlatMap().keySet()) { + BlueprintBone blueprintBone = blueprint.getFlatMap().get(bone); + if (blueprintBone != null && blueprintBone.isRenderer()) { + activeModel.getBone(bone).ifPresent(replaced -> { + if (replaced.isRenderer()) { + replaced.setModel(blueprintBone); + } + }); + } + } + } else { + for (String bonex : blueprint.getFlatMap().size() < activeModel.getBones().size() + ? blueprint.getFlatMap().keySet() + : activeModel.getBones().keySet()) { + BlueprintBone blueprintBone = blueprint.getFlatMap().get(bonex); + if (blueprintBone != null && blueprintBone.isRenderer()) { + activeModel.getBone(bonex).ifPresent(replaced -> { + if (replaced.isRenderer()) { + replaced.setModelScale(blueprintBone.getScale()); + replaced.setModel(blueprintBone); + } + }); + } + } + } + + return null; + } + } + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + ActiveModel activeModel = MythicUtils.getActiveModelOrNull(model, modelId); + if (activeModel == null) { + return SkillResult.INVALID_CONFIG; + } else { + String newModelId = MythicUtils.getOrNullLowercase(this.newModelId, meta); + ModelBlueprint blueprint = MythicUtils.getBlueprintOrNull(newModelId); + if (blueprint == null) { + return SkillResult.INVALID_CONFIG; + } else { + if (this.map != null) { + String mapId = MythicUtils.getOrNullLowercase(this.map, meta); + ModelBlueprint mapBlueprint = MythicUtils.getBlueprintOrNull(mapId); + if (mapBlueprint == null) { + return SkillResult.INVALID_CONFIG; + } + + for (String bone : mapBlueprint.getFlatMap().keySet()) { + BlueprintBone blueprintBone = blueprint.getFlatMap().get(bone); + if (blueprintBone != null && blueprintBone.isRenderer()) { + activeModel.getBone(bone).ifPresent(replaced -> { + if (replaced.isRenderer()) { + replaced.setModel(blueprintBone); + } + }); + } + } + } else { + for (String bonex : blueprint.getFlatMap().size() < activeModel.getBones().size() + ? blueprint.getFlatMap().keySet() + : activeModel.getBones().keySet()) { + BlueprintBone blueprintBone = blueprint.getFlatMap().get(bonex); + if (blueprintBone != null && blueprintBone.isRenderer()) { + activeModel.getBone(bonex).ifPresent(replaced -> { + if (replaced.isRenderer()) { + replaced.setModelScale(blueprintBone.getScale()); + replaced.setModel(blueprintBone); + } + }); + } + } + } + + return null; + } + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RendererInitMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RendererInitMechanic.java new file mode 100644 index 0000000..c200dd5 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RendererInitMechanic.java @@ -0,0 +1,46 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; + +@MythicMechanic( + name = "rendererinit", + aliases = {"renderinit"} +) +public class RendererInitMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + + public RendererInitMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + ActiveModel activeModel = MythicUtils.getActiveModelOrNull(model, modelId); + if (activeModel == null) { + return SkillResult.CONDITION_FAILED; + } else { + activeModel.initializeRenderer(); + return SkillResult.SUCCESS; + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RootMotionMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RootMotionMechanic.java new file mode 100644 index 0000000..8d6dd13 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/RootMotionMechanic.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderBoolean; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; + +@MythicMechanic( + name = "rootmotion", + aliases = {} +) +public class RootMotionMechanic implements ITargetedEntitySkill { + private final PlaceholderDouble weight; + private final PlaceholderDouble baseWeight; + private final PlaceholderBoolean override; + + public RootMotionMechanic(MythicLineConfig mlc) { + this.weight = mlc.getPlaceholderDouble(new String[]{"w", "weight"}, "-1", new String[0]); + this.baseWeight = mlc.getPlaceholderDouble(new String[]{"bw", "baseweight"}, "-1", new String[0]); + this.override = mlc.getPlaceholderBoolean(new String[]{"ov", "override"}, null); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + RootMotionHandler handler = model.getRootMotionHandler(); + double weight = this.weight == null ? -1.0 : this.weight.get(meta, target); + double baseWeight = this.baseWeight == null ? -1.0 : this.baseWeight.get(meta, target); + Boolean override = this.override == null ? null : this.override.get(meta, target); + if (weight >= 0.0) { + handler.setWeight(weight); + } + + if (baseWeight >= 0.0) { + handler.setBaseWeight(baseWeight); + } + + if (override != null) { + handler.setOverride(override); + } + + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/ScaleMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/ScaleMechanic.java new file mode 100644 index 0000000..2089957 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/ScaleMechanic.java @@ -0,0 +1,73 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; + +@MythicMechanic( + name = "scale", + aliases = {} +) +public class ScaleMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderDouble scale; + private final boolean isHitbox; + + public ScaleMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.scale = mlc.getPlaceholderDouble(new String[]{"s", "scale"}, "1", new String[0]); + this.isHitbox = mlc.getBoolean(new String[]{"h", "hitbox"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + double scale = this.scale.get(meta, target); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + MythicUtils.executeOptModelId(model, modelId, activeModel -> { + if (this.isHitbox) { + activeModel.setHitboxScale(scale); + } else { + activeModel.setScale(scale); + } + }); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + double scale = this.scale.get(meta); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + MythicUtils.executeOptModelId(model, modelId, activeModel -> { + if (this.isHitbox) { + activeModel.setHitboxScale(scale); + } else { + activeModel.setScale(scale); + } + }); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/StateMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/StateMechanic.java new file mode 100644 index 0000000..bd50a0c --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/StateMechanic.java @@ -0,0 +1,201 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.animation.BlueprintAnimation; +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.property.IAnimationProperty; +import com.ticxo.modelengine.api.generator.blueprint.ModelBlueprint; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.utils.math.Easing; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderBoolean; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; + +@MythicMechanic( + name = "state", + aliases = {"animation"} +) +public class StateMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString srcId; + private final PlaceholderString state; + private final PlaceholderString forceLoopMode; + private final PlaceholderString forceOverride; + private final PlaceholderString lerpCurveIn; + private final PlaceholderString lerpCurveOut; + private final boolean remove; + private final boolean ignoreLerp; + private final boolean force; + private final PlaceholderInt lerpIn; + private final PlaceholderInt lerpOut; + private final PlaceholderInt priority; + private final PlaceholderDouble speed; + private final PlaceholderBoolean skipLastFrame; + private final PlaceholderBoolean merge; + private final PlaceholderBoolean emptyZero; + + public StateMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.srcId = mlc.getPlaceholderString(new String[]{"src", "sid", "srcmodel", "srcmodelid"}, null, new String[0]); + this.state = mlc.getPlaceholderString(new String[]{"s", "state"}, null, new String[0]); + this.remove = mlc.getBoolean(new String[]{"r", "remove"}, false); + this.speed = mlc.getPlaceholderDouble(new String[]{"sp", "speed"}, "1", new String[0]); + this.lerpIn = mlc.getPlaceholderInteger(new String[]{"li", "lerpin"}, 0, new String[0]); + this.lerpOut = mlc.getPlaceholderInteger(new String[]{"lo", "lerpout"}, 0, new String[0]); + this.lerpCurveIn = mlc.getPlaceholderString(new String[]{"lci", "lerpcurvein"}, null, new String[0]); + this.lerpCurveOut = mlc.getPlaceholderString(new String[]{"lco", "lerpcurveout"}, null, new String[0]); + this.ignoreLerp = mlc.getBoolean(new String[]{"i", "ignorelerp"}, false); + this.force = mlc.getBoolean(new String[]{"f", "force"}, true); + this.priority = mlc.getPlaceholderInteger(new String[]{"p", "pr", "priority"}, 1, new String[0]); + this.forceLoopMode = mlc.getPlaceholderString(new String[]{"l", "loop"}, null, new String[0]); + this.forceOverride = mlc.getPlaceholderString(new String[]{"ov", "override"}, null, new String[0]); + this.skipLastFrame = mlc.getPlaceholderBoolean(new String[]{"skip", "skiplastframe"}, null); + this.merge = mlc.getPlaceholderBoolean(new String[]{"mg", "merge"}, false); + this.emptyZero = mlc.getPlaceholderBoolean(new String[]{"ez", "zero"}, null); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + return this.remove ? this.removeAnimation(meta, target) : this.addAnimation(meta, target); + } + + public SkillResult cast(SkillMetadata meta) { + return this.remove ? this.removeAnimation(meta, null) : this.addAnimation(meta, null); + } + + private SkillResult removeAnimation(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target == null ? null : target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String state = MythicUtils.getOrNullLowercase(this.state, meta, target); + if (state == null) { + return SkillResult.INVALID_CONFIG; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + String srcId = Optional.ofNullable(MythicUtils.getOrNullLowercase(this.srcId, meta, target)).orElse(modelId); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.removeAnimation(activeModel, srcId, state, meta, target)); + return SkillResult.SUCCESS; + } + } + } + + private void removeAnimation(ActiveModel activeModel, String srcId, String state, SkillMetadata meta, AbstractEntity target) { + ModelBlueprint srcBlueprint = Optional.ofNullable(MythicUtils.getBlueprintOrNull(srcId)).orElse(activeModel.getBlueprint()); + AnimationHandler handler = activeModel.getAnimationHandler(); + if (handler instanceof IStateMachineHandler stateMachineHandler) { + int priority = this.priority.get(meta, target); + if (this.ignoreLerp) { + stateMachineHandler.forceStopAnimation(priority, srcBlueprint, state); + } else { + stateMachineHandler.stopAnimation(priority, srcBlueprint, state); + } + } else if (handler instanceof IPriorityHandler priorityHandler) { + if (this.ignoreLerp) { + priorityHandler.forceStopAnimation(srcBlueprint, state); + } else { + priorityHandler.stopAnimation(srcBlueprint, state); + } + } else if (this.ignoreLerp) { + handler.forceStopAnimation(state); + } else { + handler.stopAnimation(state); + } + } + + private SkillResult addAnimation(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target == null ? null : target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String state = MythicUtils.getOrNullLowercase(this.state, meta, target); + if (state == null) { + return SkillResult.INVALID_CONFIG; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + String srcId = Optional.ofNullable(MythicUtils.getOrNullLowercase(this.srcId, meta, target)).orElse(modelId); + MythicUtils.executeOptModelId(model, modelId, activeModel -> this.addAnimation(activeModel, srcId, state, meta, target)); + return SkillResult.SUCCESS; + } + } + } + + private void addAnimation(ActiveModel activeModel, String srcId, String state, SkillMetadata meta, AbstractEntity target) { + ModelBlueprint srcBlueprint = Optional.ofNullable(MythicUtils.getBlueprintOrNull(srcId)).orElse(activeModel.getBlueprint()); + int lerpIn = this.lerpIn.get(meta, target); + int lerpOut = this.lerpOut.get(meta, target); + double speed = this.speed.get(meta, target); + BlueprintAnimation.LoopMode loopMode = BlueprintAnimation.LoopMode.getOrNull(MythicUtils.getOrNull(this.forceLoopMode, meta, target)); + BlueprintAnimation.OverrideMode override = BlueprintAnimation.OverrideMode.getOrNull(MythicUtils.getOrNull(this.forceOverride, meta, target)); + Boolean skip = this.skipLastFrame != null ? this.skipLastFrame.get(meta, target) : null; + boolean merge = this.merge != null && this.merge.get(meta, target); + Boolean emptyZero = this.emptyZero != null ? this.emptyZero.get(meta, target) : null; + Easing curveIn = Easing.getOrNull(MythicUtils.getOrNull(this.lerpCurveIn, meta, target)); + Easing curveOut = Easing.getOrNull(MythicUtils.getOrNull(this.lerpCurveOut, meta, target)); + AnimationHandler handler = activeModel.getAnimationHandler(); + if (handler instanceof IStateMachineHandler stateMachineHandler) { + int priority = this.priority.get(meta, target); + IAnimationProperty property = stateMachineHandler.playAnimation(priority, srcBlueprint, state, lerpIn * 0.05, lerpOut * 0.05, speed, this.force); + this.configProperty(loopMode, override, skip, merge, emptyZero, curveIn, curveOut, property); + } else if (handler instanceof IPriorityHandler priorityHandler) { + IAnimationProperty property = priorityHandler.playAnimation(srcBlueprint, state, lerpIn * 0.05, lerpOut * 0.05, speed, this.force); + this.configProperty(loopMode, override, skip, merge, emptyZero, curveIn, curveOut, property); + } else { + IAnimationProperty property = handler.playAnimation(state, lerpIn * 0.05, lerpOut * 0.05, speed, this.force); + this.configProperty(loopMode, override, skip, merge, emptyZero, curveIn, curveOut, property); + } + } + + private void configProperty( + BlueprintAnimation.LoopMode loopMode, + BlueprintAnimation.OverrideMode override, + Boolean skip, + boolean merge, + Boolean emptyZero, + Easing curveIn, + Easing curveOut, + IAnimationProperty property + ) { + if (property != null) { + property.setMergeLerp(merge); + if (emptyZero != null) { + property.setEmptyZero(emptyZero); + } + + property.setForceLoopMode(loopMode); + if (this.forceOverride != null) { + property.setForceOverride(override); + } + + if (skip != null) { + property.setSkipLastFrame(skip); + } + + if (curveIn != null) { + property.setLerpCurveIn(curveIn); + } + + if (curveOut != null) { + property.setLerpCurveOut(curveOut); + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/StateToggleMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/StateToggleMechanic.java new file mode 100644 index 0000000..bbce943 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/StateToggleMechanic.java @@ -0,0 +1,160 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.animation.handler.AnimationHandler; +import com.ticxo.modelengine.api.animation.handler.IStateMachineHandler; +import com.ticxo.modelengine.api.animation.property.IAnimationProperty; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.utils.math.Easing; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; + +@MythicMechanic( + name = "statetoggle", + aliases = {"togglestate"} +) +public class StateToggleMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString state; + private final PlaceholderString lerpCurveIn; + private final PlaceholderString lerpCurveOut; + private final boolean ignoreLerp; + private final boolean force; + private final PlaceholderInt lerpIn; + private final PlaceholderInt lerpOut; + private final PlaceholderInt priority; + private final PlaceholderDouble speed; + + public StateToggleMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.state = mlc.getPlaceholderString(new String[]{"s", "state"}, null, new String[0]); + this.speed = mlc.getPlaceholderDouble(new String[]{"sp", "speed"}, "1", new String[0]); + this.lerpIn = mlc.getPlaceholderInteger(new String[]{"li", "lerpin"}, 0, new String[0]); + this.lerpOut = mlc.getPlaceholderInteger(new String[]{"lo", "lerpout"}, 0, new String[0]); + this.lerpCurveIn = mlc.getPlaceholderString(new String[]{"lci", "lerpcurvein"}, null, new String[0]); + this.lerpCurveOut = mlc.getPlaceholderString(new String[]{"lco", "lerpcurveout"}, null, new String[0]); + this.ignoreLerp = mlc.getBoolean(new String[]{"i", "ignorelerp"}, false); + this.force = mlc.getBoolean(new String[]{"f", "force"}, true); + this.priority = mlc.getPlaceholderInteger(new String[]{"p", "pr", "priority"}, 1, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String state = MythicUtils.getOrNullLowercase(this.state, meta, target); + if (state == null) { + return SkillResult.INVALID_CONFIG; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + MythicUtils.executeOptModelId(model, modelId, activeModel -> { + AnimationHandler handler = activeModel.getAnimationHandler(); + if (handler instanceof IStateMachineHandler stateMachineHandler) { + if (stateMachineHandler.isPlayingAnimation(state)) { + this.removeAnimation(stateMachineHandler, state, meta, target); + } else { + this.addAnimation(stateMachineHandler, state, meta, target); + } + } else if (handler.isPlayingAnimation(state)) { + this.removeAnimation(handler, state); + } else { + this.addAnimation(handler, state, meta, target); + } + }); + return SkillResult.SUCCESS; + } + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String state = MythicUtils.getOrNullLowercase(this.state, meta); + if (state == null) { + return SkillResult.INVALID_CONFIG; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + MythicUtils.executeOptModelId(model, modelId, activeModel -> { + AnimationHandler handler = activeModel.getAnimationHandler(); + if (handler instanceof IStateMachineHandler stateMachineHandler) { + if (stateMachineHandler.isPlayingAnimation(state)) { + this.removeAnimation(stateMachineHandler, state, meta, null); + } else { + this.addAnimation(stateMachineHandler, state, meta, null); + } + } else if (handler.isPlayingAnimation(state)) { + this.removeAnimation(handler, state); + } else { + this.addAnimation(handler, state, meta, null); + } + }); + return SkillResult.SUCCESS; + } + } + } + + private void removeAnimation(AnimationHandler handler, String state) { + if (this.ignoreLerp) { + handler.forceStopAnimation(state); + } else { + handler.stopAnimation(state); + } + } + + private void removeAnimation(IStateMachineHandler handler, String state, SkillMetadata meta, AbstractEntity target) { + int priority = this.priority.get(meta, target); + if (this.ignoreLerp) { + handler.forceStopAnimation(priority, state); + } else { + handler.stopAnimation(priority, state); + } + } + + private void addAnimation(AnimationHandler handler, String state, SkillMetadata meta, AbstractEntity target) { + int lerpIn = this.lerpIn.get(meta, target); + int lerpOut = this.lerpOut.get(meta, target); + double speed = this.speed.get(meta, target); + this.configProperty(handler.playAnimation(state, lerpIn * 0.05, lerpOut * 0.05, speed, this.force), meta, target); + } + + private void addAnimation(IStateMachineHandler handler, String state, SkillMetadata meta, AbstractEntity target) { + int lerpIn = this.lerpIn.get(meta, target); + int lerpOut = this.lerpOut.get(meta, target); + double speed = this.speed.get(meta, target); + int priority = this.priority.get(meta, target); + this.configProperty(handler.playAnimation(priority, state, lerpIn * 0.05, lerpOut * 0.05, speed, this.force), meta, target); + } + + private void configProperty(IAnimationProperty property, SkillMetadata meta, AbstractEntity target) { + if (property != null) { + Easing curveIn = Easing.getOrNull(MythicUtils.getOrNull(this.lerpCurveIn, meta, target)); + if (curveIn != null) { + property.setLerpCurveIn(curveIn); + } + + Easing curveOut = Easing.getOrNull(MythicUtils.getOrNull(this.lerpCurveOut, meta, target)); + if (curveOut != null) { + property.setLerpCurveOut(curveOut); + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/SubModelMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/SubModelMechanic.java new file mode 100644 index 0000000..d772b6d --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/SubModelMechanic.java @@ -0,0 +1,109 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.generator.blueprint.BlueprintBone; +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.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; + +@MythicMechanic( + name = "submodel", + aliases = {} +) +public class SubModelMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString parentId; + private final PlaceholderString childId; + private final PlaceholderString prefix; + private final boolean remove; + + public SubModelMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.parentId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, null, new String[0]); + this.childId = mlc.getPlaceholderString(new String[]{"sp", "spid", "subpart", "subpartid"}, null, new String[0]); + this.prefix = mlc.getPlaceholderString(new String[]{"pfx", "prefix"}, "", new String[0]); + this.remove = mlc.getBoolean(new String[]{"r", "remove"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, target.getUniqueId()); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + ActiveModel activeModel = MythicUtils.getActiveModelOrNull(model, modelId); + if (activeModel == null) { + return SkillResult.CONDITION_FAILED; + } else { + String childId = MythicUtils.getOrNullLowercase(this.childId, meta, target); + if (childId == null) { + return SkillResult.INVALID_CONFIG; + } else { + if (this.remove) { + activeModel.getBone(childId).ifPresent(ModelBone::destroy); + } else { + String parentId = MythicUtils.getOrNullLowercase(this.parentId, meta, target); + String prefix = MythicUtils.getOrNullLowercase(this.prefix, meta, target); + BlueprintBone childBone = activeModel.getBlueprint().getFlatMap().get(childId); + if (childBone == null) { + return SkillResult.INVALID_CONFIG; + } + + activeModel.forceGenerateBone(parentId, prefix, childBone); + } + + return SkillResult.SUCCESS; + } + } + } + } + + public SkillResult cast(SkillMetadata meta) { + Optional maybeModel = MythicUtils.findSkillableModel(meta, null); + if (maybeModel.isEmpty()) { + return SkillResult.CONDITION_FAILED; + } else { + ModeledEntity model = maybeModel.get(); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + ActiveModel activeModel = MythicUtils.getActiveModelOrNull(model, modelId); + if (activeModel == null) { + return SkillResult.CONDITION_FAILED; + } else { + String childId = MythicUtils.getOrNullLowercase(this.childId, meta); + if (childId == null) { + return SkillResult.INVALID_CONFIG; + } else { + if (this.remove) { + activeModel.getBone(childId).ifPresent(ModelBone::destroy); + } else { + String parentId = MythicUtils.getOrNullLowercase(this.parentId, meta); + String prefix = MythicUtils.getOrNullLowercase(this.prefix, meta); + BlueprintBone childBone = activeModel.getBlueprint().getFlatMap().get(childId); + if (childBone == null) { + return SkillResult.INVALID_CONFIG; + } + + activeModel.forceGenerateBone(parentId, prefix, childBone); + } + + return SkillResult.SUCCESS; + } + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/SwapEntityMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/SwapEntityMechanic.java new file mode 100644 index 0000000..9aae7ea --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/model/SwapEntityMechanic.java @@ -0,0 +1,75 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.model; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; + +@MythicMechanic( + name = "swapentity", + aliases = {} +) +public class SwapEntityMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final boolean hitbox; + private final boolean invisible; + private final PlaceholderDouble stepHeight; + private final PlaceholderInt viewRadius; + + public SwapEntityMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.hitbox = mlc.getBoolean(new String[]{"h", "hitbox"}, true); + this.invisible = mlc.getBoolean(new String[]{"i", "invis", "invisible"}, true); + this.stepHeight = mlc.getPlaceholderDouble(new String[]{"s", "step"}, "0.5", new String[0]); + this.viewRadius = mlc.getPlaceholderInteger(new String[]{"rad", "radius"}, 0, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + AbstractEntity caster = meta.getCaster().getEntity(); + ModeledEntity casterModel = ModelEngineAPI.getModeledEntity(caster.getUniqueId()); + if (casterModel == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + if (modelId == null) { + return SkillResult.INVALID_CONFIG; + } else if (!casterModel.getModels().containsKey(modelId)) { + return SkillResult.INVALID_CONFIG; + } else { + ModeledEntity targetModel = ModelEngineAPI.getOrCreateModeledEntity(target.getBukkitEntity()); + if (targetModel.getModel(modelId).isPresent()) { + return SkillResult.CONDITION_FAILED; + } else { + double stepHeight = this.stepHeight.get(meta, target); + int viewRadius = this.viewRadius.get(meta, target); + Optional maybeModel = casterModel.removeModel(modelId); + maybeModel.ifPresent(activeModel -> { + targetModel.setBaseEntityVisible(!this.invisible); + targetModel.getBase().setMaxStepHeight(stepHeight); + if (viewRadius > 0) { + targetModel.getBase().setRenderRadius(viewRadius); + } + + targetModel.addModel(activeModel, this.hitbox).ifPresent(ActiveModel::destroy); + }); + return SkillResult.SUCCESS; + } + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/DismountAllMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/DismountAllMechanic.java new file mode 100644 index 0000000..6f51e58 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/DismountAllMechanic.java @@ -0,0 +1,67 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.mounting; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; + +@MythicMechanic( + name = "dismountallmodel", + aliases = {"dismountall"} +) +public class DismountAllMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderString pBone; + + public DismountAllMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.pBone = mlc.getPlaceholderString(new String[]{"p", "pbone", "seat"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + if (ServerInfo.scheduleOnRegion(target.getBukkitEntity(), () -> this.castAtEntity(meta, target))) { + return SkillResult.SUCCESS; + } else { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + if (modelId == null) { + return SkillResult.INVALID_CONFIG; + } else { + this.dismountLogic(meta, target, modelId); + return SkillResult.SUCCESS; + } + } + } + } + + private void dismountLogic(SkillMetadata meta, AbstractEntity target, String modelId) { + ModelEngineAPI.getModeledEntity(target.getUniqueId()) + .getModel(modelId) + .ifPresent(activeModel -> activeModel.getMountManager().ifPresent(mountManager -> { + String parts = MythicUtils.getOrNullLowercase(this.pBone, meta, target); + if (parts != null) { + for (String seat : parts.split(",")) { + ((MountManager)mountManager).dismountPassengers(seat); + } + } else { + ((MountManager)mountManager).dismountAll(); + } + })); + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/DismountModelMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/DismountModelMechanic.java new file mode 100644 index 0000000..417fc72 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/DismountModelMechanic.java @@ -0,0 +1,86 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.mounting; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.Optional; +import org.bukkit.entity.Entity; + +@MythicMechanic( + name = "dismountmodel", + aliases = {} +) +public class DismountModelMechanic implements ITargetedEntitySkill { + private final boolean driver; + private PlaceholderString modelId; + private PlaceholderString pBone; + + public DismountModelMechanic(MythicLineConfig mlc) { + this.driver = mlc.getBoolean(new String[]{"d", "drive", "driver"}, true); + if (!this.driver) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.pBone = mlc.getPlaceholderString(new String[]{"p", "pbone", "seat"}, null, new String[0]); + } + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + if (ServerInfo.scheduleOnRegion(target.getBukkitEntity(), () -> this.castAtEntity(meta, target))) { + return SkillResult.SUCCESS; + } else { + ModeledEntity model = ModelEngineAPI.getModeledEntity(meta.getCaster().getEntity().getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else if (this.driver) { + ((MountManager)((MountData)model.getMountData()).getMainMountManager()).dismountDriver(); + return SkillResult.SUCCESS; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + model.getModel(modelId).ifPresent(activeModel -> activeModel.getMountManager().ifPresent(mountManager -> { + Entity entity = target.getBukkitEntity(); + String part = MythicUtils.getOrNullLowercase(this.pBone, meta, target); + if (part == null) { + ((MountManager)mountManager).dismountRider(entity); + } else { + String[] seats = part.split(","); + Optional maybeMount = ((MountManager)mountManager).getMount(entity); + maybeMount.ifPresent(mount -> { + if (this.contains(((com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior)mount).getBone().getUniqueBoneId(), seats)) { + ((MountManager)mountManager).dismountRider(entity); + } + }); + } + })); + return SkillResult.SUCCESS; + } + } + } + + public boolean getTargetsCreatives() { + return true; + } + + private boolean contains(String seat, String... seats) { + for (String s : seats) { + if (seat.equals(s)) { + return true; + } + } + + return false; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/MountModelMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/MountModelMechanic.java new file mode 100644 index 0000000..5a117a8 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/mounting/MountModelMechanic.java @@ -0,0 +1,179 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.mounting; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.mount.controller.MountControllerSupplier; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.packs.Pack; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.Skill; +import io.lumine.mythic.api.skills.SkillHolder; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.bukkit.events.MythicMechanicLoadEvent; +import io.lumine.mythic.core.skills.SkillExecutor; +import java.io.File; +import java.util.List; +import java.util.Optional; + +@MythicMechanic( + name = "mountmodel", + aliases = {} +) +public class MountModelMechanic implements ITargetedEntitySkill, SkillHolder { + private final boolean isDriver; + private final boolean force; + private final boolean autoDismount; + private final boolean canDamageMount; + private final boolean canInteractMount; + private final PlaceholderString mode; + private final PlaceholderString modelId; + private Skill controllerSkill; + private PlaceholderString pbone; + + public MountModelMechanic(MythicMechanicLoadEvent event) { + File file = event.getContainer().getFile(); + SkillExecutor manager = event.getContainer().getManager(); + MythicLineConfig mlc = event.getConfig(); + this.isDriver = mlc.getBoolean(new String[]{"d", "drive", "driver"}, true); + this.force = mlc.getBoolean(new String[]{"f", "force"}, false); + this.autoDismount = mlc.getBoolean(new String[]{"ad", "autodismount"}, false); + this.canDamageMount = mlc.getBoolean(new String[]{"dmg", "damagemount"}, false); + this.canInteractMount = mlc.getBoolean(new String[]{"int", "interactmount"}, false); + this.mode = mlc.getPlaceholderString(new String[]{"m", "mode"}, "walking", new String[0]); + this.modelId = mlc.getPlaceholderString(new String[]{"mid", "model", "modelid"}, null, new String[0]); + if (!this.isDriver) { + this.pbone = mlc.getPlaceholderString(new String[]{"p", "pbone", "seat"}, null, new String[0]); + } + + manager.queueSecondPass(() -> manager.getSkill(file, this, this.mode.serialize()).ifPresent(skill -> { + this.controllerSkill = skill; + if (this.controllerSkill.isInlineSkill()) { + this.controllerSkill.addParent(this); + } + })); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + if (ServerInfo.scheduleOnRegion(target.getBukkitEntity(), () -> this.castAtEntity(meta, target))) { + return SkillResult.SUCCESS; + } else { + AbstractEntity caster = meta.getCaster().getEntity(); + ModeledEntity model = ModelEngineAPI.getModeledEntity(caster.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String controllerId = MythicUtils.getOrNullLowercase(this.mode, meta, target); + MountControllerSupplier controllerType = this.controllerSkill != null + ? MythicUtils.createControllerSupplier(this.controllerSkill, meta) + : ModelEngineAPI.getMountControllerTypeRegistry().get(controllerId); + if (this.isDriver) { + GlobalBehaviorData mountData = model.getMountData(); + BehaviorManager mountManager = ((MountData)mountData).getMainMountManager(); + if (mountManager == null) { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + Optional maybeModel = model.getModel(modelId); + if (maybeModel.isPresent()) { + Optional maybeManager = maybeModel.get().getMountManager(); + if (maybeManager.isPresent()) { + mountManager = (BehaviorManager)maybeManager.get(); + } + } + } + + if (mountManager == null) { + return SkillResult.CONDITION_FAILED; + } + + if (!((MountManager)mountManager).canDrive()) { + return SkillResult.CONDITION_FAILED; + } + + if (!this.force && ((MountManager)mountManager).isControlled()) { + return SkillResult.CONDITION_FAILED; + } + + if (this.tryDismountOld(target)) { + ((MountManager)mountManager).dismountDriver(); + ((MountManager)mountManager).mountDriver(target.getBukkitEntity(), controllerType, mountController -> { + mountController.setCanDamageMount(this.canDamageMount); + mountController.setCanInteractMount(this.canInteractMount); + }); + } + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + String pbone = MythicUtils.getOrNullLowercase(this.pbone, meta, target); + if (modelId == null || pbone == null) { + return SkillResult.INVALID_CONFIG; + } + + List seats = List.of(pbone.split(",")); + model.getModel(modelId).ifPresent(activeModel -> activeModel.getMountManager().ifPresent(mountManagerx -> { + if (((MountManager)mountManagerx).canRide()) { + if (this.tryDismountOld(target)) { + if (this.force) { + ((MountManager)mountManagerx).mountLeastOccupied(target.getBukkitEntity(), seats, controllerType, mountController -> { + mountController.setCanDamageMount(this.canDamageMount); + mountController.setCanInteractMount(this.canInteractMount); + }); + } else { + ((MountManager)mountManagerx).mountAvailable(target.getBukkitEntity(), seats, controllerType, mountController -> { + mountController.setCanDamageMount(this.canDamageMount); + mountController.setCanInteractMount(this.canInteractMount); + }); + } + } + } + })); + } + + return SkillResult.SUCCESS; + } + } + } + + private boolean tryDismountOld(AbstractEntity target) { + ActiveModel model = ModelEngineAPI.getMountPairManager().getMountedPair(target.getUniqueId()); + if (model == null) { + return true; + } else if (this.autoDismount) { + Optional maybeManager = model.getMountManager(); + if (maybeManager.isEmpty()) { + return false; + } else { + BehaviorManager mountManager = (BehaviorManager)maybeManager.get(); + ((MountManager)mountManager).dismountRider(target.getBukkitEntity()); + return true; + } + } else { + return false; + } + } + + public boolean getTargetsCreatives() { + return true; + } + + public String getInternalName() { + return "Unknown/mountModel"; + } + + public Pack getPack() { + return null; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/nametag/SetNametagMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/nametag/SetNametagMechanic.java new file mode 100644 index 0000000..69819cd --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/nametag/SetNametagMechanic.java @@ -0,0 +1,105 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.nametag; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.type.NameTag; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.adapters.AbstractVector; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.api.skills.placeholders.PlaceholderVector; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.bukkit.entity.Display.Billboard; +import org.bukkit.entity.TextDisplay.TextAlignment; + +@MythicMechanic( + name = "setmodeltag", + aliases = {} +) +public class SetNametagMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderString tag; + private final boolean visible; + private final Integer backgroundColor; + private final boolean useDefaultBackgroundColor; + private final TextAlignment alignment; + private final Billboard billboard; + private final PlaceholderVector scale; + private final boolean seeThrough; + private final byte textOpacity; + private final boolean shadow; + private final int lineWidth; + + public SetNametagMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"b", "bone", "p", "pid", "part", "partid"}, null, new String[0]); + this.tag = mlc.getPlaceholderString(new String[]{"t", "tag"}, null, new String[0]); + this.visible = mlc.getBoolean(new String[]{"v", "visible"}, true); + this.backgroundColor = mlc.getInteger(new String[]{"background", "backgroundcolor"}, 0); + this.useDefaultBackgroundColor = mlc.getBoolean(new String[]{"usedefaultbackground", "defaultbackground", "db"}, true); + this.alignment = (TextAlignment)mlc.getEnum(new String[]{"align", "alignment"}, TextAlignment.class, TextAlignment.CENTER); + this.billboard = (Billboard)mlc.getEnum(new String[]{"billboard"}, Billboard.class, Billboard.CENTER); + this.scale = mlc.getPlaceholderVector(new String[]{"scale"}, "1,1,1"); + this.seeThrough = mlc.getBoolean(new String[]{"seethrough"}, true); + this.textOpacity = (byte)mlc.getInteger(new String[]{"opacity", "textopacity"}, -1); + this.shadow = mlc.getBoolean(new String[]{"shadow"}, false); + this.lineWidth = mlc.getInteger(new String[]{"linewidth"}, 200); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + model.getModel(modelId) + .ifPresent( + activeModel -> { + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + activeModel.getBone(partId) + .flatMap(modelBone -> modelBone.getBoneBehavior(BoneBehaviorTypes.NAMETAG)) + .ifPresent( + nameTag -> { + ((NameTag)nameTag) + .setComponentSupplier( + this.tag == null + ? null + : () -> { + String raw = this.tag.get(meta, target); + return (Component)(raw.indexOf(167) >= 0 + ? LegacyComponentSerializer.legacySection().deserialize(raw) + : MiniMessage.miniMessage().deserialize(raw)); + } + ); + ((NameTag)nameTag).setVisible(this.visible); + ((NameTag)nameTag).setBackgroundColor(this.backgroundColor); + ((NameTag)nameTag).setUseDefaultBackgroundColor(this.useDefaultBackgroundColor); + ((NameTag)nameTag).setAlignment(this.alignment); + ((NameTag)nameTag).setBillboard(this.billboard); + ((NameTag)nameTag).setScale(((AbstractVector)this.scale.get()).toVector3f()); + ((NameTag)nameTag).setSeeThrough(this.seeThrough); + ((NameTag)nameTag).setTextOpacity(this.textOpacity); + ((NameTag)nameTag).setShadow(this.shadow); + ((NameTag)nameTag).setLineWidth(this.lineWidth); + } + ); + } + ); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/nametag/SetNametagVisibilityMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/nametag/SetNametagVisibilityMechanic.java new file mode 100644 index 0000000..d68f8a2 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/nametag/SetNametagVisibilityMechanic.java @@ -0,0 +1,54 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.nametag; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.type.NameTag; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; + +@MythicMechanic( + name = "setmodeltagvisible", + aliases = {} +) +public class SetNametagVisibilityMechanic implements ITargetedEntitySkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final boolean visible; + + public SetNametagVisibilityMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"b", "bone", "p", "pid", "part", "partid"}, null, new String[0]); + this.visible = mlc.getBoolean(new String[]{"v", "visible"}, true); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + ModeledEntity model = ModelEngineAPI.getModeledEntity(target.getUniqueId()); + if (model == null) { + return SkillResult.CONDITION_FAILED; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + model.getModel(modelId) + .ifPresent( + activeModel -> { + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + activeModel.getBone(partId) + .flatMap(modelBone -> modelBone.getBoneBehavior(BoneBehaviorTypes.NAMETAG)) + .ifPresent(nameTag -> ((NameTag)nameTag).setVisible(this.visible)); + } + ); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXBrightnessMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXBrightnessMechanic.java new file mode 100644 index 0000000..71298df --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXBrightnessMechanic.java @@ -0,0 +1,56 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import java.util.UUID; + +@MythicMechanic( + name = "vfxbrightness", + aliases = {"vfxlight"} +) +public class VFXBrightnessMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderInt blockLight; + private final PlaceholderInt skyLight; + + public VFXBrightnessMechanic(MythicLineConfig mlc) { + this.blockLight = mlc.getPlaceholderInteger(new String[]{"block", "b"}, -1, new String[0]); + this.skyLight = mlc.getPlaceholderInteger(new String[]{"sky", "s"}, -1, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + VFX vfx = ModelEngineAPI.getVFX(target.getBukkitEntity()); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setBlockLight(this.blockLight.get(meta, target)); + vfx.setSkyLight(this.skyLight.get(meta, target)); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setBlockLight(this.blockLight.get(meta)); + vfx.setSkyLight(this.skyLight.get(meta)); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXChangeModelMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXChangeModelMechanic.java new file mode 100644 index 0000000..fe95e05 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXChangeModelMechanic.java @@ -0,0 +1,66 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.UUID; + +@MythicMechanic( + name = "vfxchangemodel", + aliases = {} +) +public class VFXChangeModelMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + + public VFXChangeModelMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, null, new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + if (modelId != null && partId != null) { + VFX vfx = ModelEngineAPI.getVFX(target.getBukkitEntity()); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.useModel(modelId, partId); + return SkillResult.SUCCESS; + } + } else { + return SkillResult.INVALID_CONFIG; + } + } + + public SkillResult cast(SkillMetadata meta) { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta); + if (modelId != null && partId != null) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.useModel(modelId, partId); + return SkillResult.SUCCESS; + } + } else { + return SkillResult.INVALID_CONFIG; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXEnchantMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXEnchantMechanic.java new file mode 100644 index 0000000..56f7693 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXEnchantMechanic.java @@ -0,0 +1,51 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import java.util.UUID; + +@MythicMechanic( + name = "vfxenchant", + aliases = {} +) +public class VFXEnchantMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final boolean enchant; + + public VFXEnchantMechanic(MythicLineConfig mlc) { + this.enchant = mlc.getBoolean(new String[]{"e", "en", "enchant"}, true); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + VFX vfx = ModelEngineAPI.getVFX(target.getBukkitEntity()); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setEnchanted(this.enchant); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setEnchanted(this.enchant); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXMechanic.java new file mode 100644 index 0000000..47dc355 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXMechanic.java @@ -0,0 +1,128 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.compatibility.ProjectileEntity; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.core.skills.projectiles.ProjectileBulletableTracker; +import java.util.UUID; +import org.bukkit.Color; + +@MythicMechanic( + name = "vfx", + aliases = {} +) +public class VFXMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final boolean remove; + private final PlaceholderInt radius; + private final PlaceholderString color; + private final boolean enchant; + private final boolean visible; + private final boolean baseVisible; + + public VFXMechanic(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, null, new String[0]); + this.remove = mlc.getBoolean(new String[]{"r", "remove"}, false); + this.radius = mlc.getPlaceholderInteger(new String[]{"rad", "radius"}, 0, new String[0]); + this.color = mlc.getPlaceholderString(new String[]{"c", "color"}, "FFFFFF", new String[0]); + this.enchant = mlc.getBoolean(new String[]{"en", "enchant"}, false); + this.visible = mlc.getBoolean(new String[]{"v", "visible"}, true); + this.baseVisible = mlc.getBoolean(new String[]{"bv", "bvisible"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + if (ServerInfo.scheduleOnRegion(target.getBukkitEntity(), () -> this.castAtEntity(meta, target))) { + return SkillResult.SUCCESS; + } else if (this.remove) { + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(target.getUniqueId()); + if (vfx == null) { + return SkillResult.CONDITION_FAILED; + } else { + vfx.markRemoved(); + return SkillResult.SUCCESS; + } + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta, target); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta, target); + if (modelId != null && partId != null) { + int radius = this.radius.get(meta, target); + Color color = MythicUtils.getColor(MythicUtils.getOrNull(this.color, meta, target)); + ModelEngineAPI.createVFX(target.getBukkitEntity(), vfx -> { + BodyRotationController brc = vfx.getBase().getBodyRotationController(); + brc.setYBodyRot(brc.getYHeadRot()); + vfx.useModel(modelId, partId); + if (radius > 0) { + vfx.getBase().setRenderRadius(radius); + } + + vfx.setColor(color); + vfx.setEnchanted(this.enchant); + vfx.setVisible(this.visible); + vfx.setBaseEntityVisible(this.baseVisible); + }); + return SkillResult.SUCCESS; + } else { + return SkillResult.INVALID_CONFIG; + } + } + } + + public SkillResult cast(SkillMetadata meta) { + if (meta.getCallingEvent() instanceof ProjectileBulletableTracker projectileTracker) { + if (this.remove) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.CONDITION_FAILED; + } else { + vfx.markRemoved(); + return SkillResult.SUCCESS; + } + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, meta); + String partId = MythicUtils.getOrNullLowercase(this.partId, meta); + if (modelId != null && partId != null) { + int radius = this.radius.get(meta); + Color color = MythicUtils.getColor(MythicUtils.getOrNull(this.color, meta)); + MythicUtils.castProjectileEntity(projectileTracker).ifPresent(tracker -> ModelEngineAPI.createVFX(new ProjectileEntity(tracker), vfx -> { + BodyRotationController brc = vfx.getBase().getBodyRotationController(); + brc.setYBodyRot(brc.getYHeadRot()); + vfx.useModel(modelId, partId); + if (radius > 0) { + vfx.getBase().setRenderRadius(radius); + } + + vfx.setColor(color); + vfx.setEnchanted(this.enchant); + vfx.setVisible(this.visible); + vfx.setBaseEntityVisible(this.baseVisible); + })); + return SkillResult.SUCCESS; + } else { + return SkillResult.INVALID_CONFIG; + } + } + } else { + return SkillResult.INVALID_TARGET; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetPositionMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetPositionMechanic.java new file mode 100644 index 0000000..3dceac7 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetPositionMechanic.java @@ -0,0 +1,45 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import java.util.UUID; +import org.joml.Vector3f; + +@MythicMechanic( + name = "vfxposreset", + aliases = {} +) +public class VFXResetPositionMechanic implements ITargetedEntitySkill, INoTargetSkill { + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + VFX vfx = ModelEngineAPI.getVFX(target.getBukkitEntity()); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setPosition(new Vector3f()); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setPosition(new Vector3f()); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetRotationMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetRotationMechanic.java new file mode 100644 index 0000000..97f3e45 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetRotationMechanic.java @@ -0,0 +1,45 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import java.util.UUID; +import org.joml.Vector3f; + +@MythicMechanic( + name = "vfxrotreset", + aliases = {} +) +public class VFXResetRotationMechanic implements ITargetedEntitySkill, INoTargetSkill { + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + VFX vfx = ModelEngineAPI.getVFX(target.getBukkitEntity()); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setRotation(new Vector3f()); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setRotation(new Vector3f()); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetScaleMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetScaleMechanic.java new file mode 100644 index 0000000..2c56c0d --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXResetScaleMechanic.java @@ -0,0 +1,45 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import java.util.UUID; +import org.joml.Vector3f; + +@MythicMechanic( + name = "vfxscalereset", + aliases = {"vfxsclreset", "vfxscareset"} +) +public class VFXResetScaleMechanic implements ITargetedEntitySkill, INoTargetSkill { + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + VFX vfx = ModelEngineAPI.getVFX(target.getBukkitEntity()); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setScale(new Vector3f(1.0F)); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setScale(new Vector3f(1.0F)); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetPositionMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetPositionMechanic.java new file mode 100644 index 0000000..51232c4 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetPositionMechanic.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import java.util.UUID; +import org.joml.Vector3f; + +@MythicMechanic( + name = "vfxpos", + aliases = {} +) +public class VFXSetPositionMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final boolean relative; + private PlaceholderDouble x; + private PlaceholderDouble y; + private PlaceholderDouble z; + + public VFXSetPositionMechanic(MythicLineConfig mlc) { + String coords = mlc.getString(new String[]{"p", "pos", "position"}, null, new String[0]); + if (coords != null) { + String[] split = coords.split(","); + + try { + this.x = PlaceholderDouble.of(split[0]); + this.y = PlaceholderDouble.of(split[1]); + this.z = PlaceholderDouble.of(split[2]); + } catch (Exception var5) { + TLogger.error("The 'position' attribute must be in the format p=x,y,z."); + this.x = PlaceholderDouble.of("0"); + this.y = PlaceholderDouble.of("0"); + this.z = PlaceholderDouble.of("0"); + } + } else { + this.x = mlc.getPlaceholderDouble("x", "0"); + this.y = mlc.getPlaceholderDouble("y", "0"); + this.z = mlc.getPlaceholderDouble("z", "0"); + } + + this.relative = mlc.getBoolean(new String[]{"r", "rel", "relative"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + VFX vfx = ModelEngineAPI.getVFX(target.getBukkitEntity()); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + if (this.relative) { + vfx.getPosition().add((float)this.x.get(meta, target), (float)this.y.get(meta, target), (float)this.z.get(meta, target)); + } else { + vfx.setPosition(new Vector3f((float)this.x.get(meta, target), (float)this.y.get(meta, target), (float)this.z.get(meta, target))); + } + + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + if (this.relative) { + vfx.getPosition().add((float)this.x.get(meta), (float)this.y.get(meta), (float)this.z.get(meta)); + } else { + vfx.setPosition(new Vector3f((float)this.x.get(meta), (float)this.y.get(meta), (float)this.z.get(meta))); + } + + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetRotationMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetRotationMechanic.java new file mode 100644 index 0000000..a600f97 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetRotationMechanic.java @@ -0,0 +1,131 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import java.util.UUID; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +@MythicMechanic( + name = "vfxrot", + aliases = {} +) +public class VFXSetRotationMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final boolean relative; + private final boolean newOrigin; + private PlaceholderDouble x; + private PlaceholderDouble y; + private PlaceholderDouble z; + + public VFXSetRotationMechanic(MythicLineConfig mlc) { + String coords = mlc.getString(new String[]{"r", "rot", "rotation"}, null, new String[0]); + if (coords != null) { + String[] split = coords.split(","); + + try { + this.x = PlaceholderDouble.of(split[0]); + this.y = PlaceholderDouble.of(split[1]); + this.z = PlaceholderDouble.of(split[2]); + } catch (Exception var5) { + TLogger.error("The 'rotation' attribute must be in the format r=x,y,z."); + this.x = PlaceholderDouble.of("0"); + this.y = PlaceholderDouble.of("0"); + this.z = PlaceholderDouble.of("0"); + } + } else { + this.x = mlc.getPlaceholderDouble("x", "0"); + this.y = mlc.getPlaceholderDouble("y", "0"); + this.z = mlc.getPlaceholderDouble("z", "0"); + } + + this.relative = mlc.getBoolean(new String[]{"rel", "relative"}, false); + this.newOrigin = mlc.getBoolean(new String[]{"neworigin", "origin", "o"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + VFX vfx = ModelEngineAPI.getVFX(target.getBukkitEntity()); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + if (this.relative) { + Vector3f r = vfx.getRotation(); + Quaternionf original = new Quaternionf().rotationZYX(r.z, r.y, r.x); + Quaternionf delta = new Quaternionf() + .rotationZYX( + (float)this.z.get(meta, target) * (float) (Math.PI / 180.0), + (float)this.y.get(meta, target) * (float) (Math.PI / 180.0), + (float)this.x.get(meta, target) * (float) (Math.PI / 180.0) + ); + if (this.newOrigin) { + original.mul(delta); + TMath.getEulerAnglesZYX(original, r); + } else { + delta.mul(original); + TMath.getEulerAnglesZYX(delta, r); + } + } else { + vfx.setRotation( + new Vector3f( + (float)this.x.get(meta, target) * (float) (Math.PI / 180.0), + (float)this.y.get(meta, target) * (float) (Math.PI / 180.0), + (float)this.z.get(meta, target) * (float) (Math.PI / 180.0) + ) + ); + } + + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + if (this.relative) { + Vector3f r = vfx.getRotation(); + Quaternionf original = new Quaternionf().rotationZYX(r.z, r.y, r.x); + Quaternionf delta = new Quaternionf() + .rotationZYX( + (float)this.z.get(meta) * (float) (Math.PI / 180.0), + (float)this.y.get(meta) * (float) (Math.PI / 180.0), + (float)this.x.get(meta) * (float) (Math.PI / 180.0) + ); + if (this.newOrigin) { + original.mul(delta); + TMath.getEulerAnglesZYX(original, r); + } else { + delta.mul(original); + TMath.getEulerAnglesZYX(delta, r); + } + } else { + vfx.setRotation( + new Vector3f( + (float)this.x.get(meta) * (float) (Math.PI / 180.0), + (float)this.y.get(meta) * (float) (Math.PI / 180.0), + (float)this.z.get(meta) * (float) (Math.PI / 180.0) + ) + ); + } + + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetScaleMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetScaleMechanic.java new file mode 100644 index 0000000..06c3798 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetScaleMechanic.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import java.util.UUID; +import org.joml.Vector3f; + +@MythicMechanic( + name = "vfxscale", + aliases = {"vfxscl", "vfxsca"} +) +public class VFXSetScaleMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final boolean relative; + private PlaceholderDouble x; + private PlaceholderDouble y; + private PlaceholderDouble z; + + public VFXSetScaleMechanic(MythicLineConfig mlc) { + String coords = mlc.getString(new String[]{"s", "sca", "scl", "scale"}, null, new String[0]); + if (coords != null) { + String[] split = coords.split(","); + + try { + this.x = PlaceholderDouble.of(split[0]); + this.y = PlaceholderDouble.of(split[1]); + this.z = PlaceholderDouble.of(split[2]); + } catch (Exception var5) { + TLogger.error("The 'scale' attribute must be in the format s=x,y,z."); + this.x = PlaceholderDouble.of("0"); + this.y = PlaceholderDouble.of("0"); + this.z = PlaceholderDouble.of("0"); + } + } else { + this.x = mlc.getPlaceholderDouble("x", "0"); + this.y = mlc.getPlaceholderDouble("y", "0"); + this.z = mlc.getPlaceholderDouble("z", "0"); + } + + this.relative = mlc.getBoolean(new String[]{"r", "rel", "relative"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + VFX vfx = ModelEngineAPI.getVFX(target.getBukkitEntity()); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + if (this.relative) { + vfx.getScale().add((float)this.x.get(meta, target), (float)this.y.get(meta, target), (float)this.z.get(meta, target)); + } else { + vfx.setScale(new Vector3f((float)this.x.get(meta, target), (float)this.y.get(meta, target), (float)this.z.get(meta, target))); + } + + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + if (this.relative) { + vfx.getScale().add((float)this.x.get(meta), (float)this.y.get(meta), (float)this.z.get(meta)); + } else { + vfx.setScale(new Vector3f((float)this.x.get(meta), (float)this.y.get(meta), (float)this.z.get(meta))); + } + + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetVisibilityMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetVisibilityMechanic.java new file mode 100644 index 0000000..8d26cd2 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXSetVisibilityMechanic.java @@ -0,0 +1,51 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import java.util.UUID; + +@MythicMechanic( + name = "vfxsetvis", + aliases = {} +) +public class VFXSetVisibilityMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final boolean vis; + + public VFXSetVisibilityMechanic(MythicLineConfig mlc) { + this.vis = mlc.getBoolean(new String[]{"v", "visible"}, false); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + VFX vfx = ModelEngineAPI.getVFX(target.getBukkitEntity()); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setVisible(this.vis); + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + vfx.setVisible(this.vis); + return SkillResult.SUCCESS; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXTintMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXTintMechanic.java new file mode 100644 index 0000000..64102b8 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/mechanics/vfx/VFXTintMechanic.java @@ -0,0 +1,129 @@ +package com.ticxo.modelengine.core21.mythic.mechanics.vfx; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.utils.scheduling.PlatformScheduler; +import com.ticxo.modelengine.api.utils.scheduling.PlatformTask; +import com.ticxo.modelengine.api.vfx.VFX; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicMechanic; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.INoTargetSkill; +import io.lumine.mythic.api.skills.ITargetedEntitySkill; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.SkillResult; +import io.lumine.mythic.api.skills.ThreadSafetyLevel; +import io.lumine.mythic.api.skills.placeholders.PlaceholderInt; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import java.util.UUID; +import org.bukkit.Color; + +@MythicMechanic( + name = "vfxtint", + aliases = {"vfxcolor"} +) +public class VFXTintMechanic implements ITargetedEntitySkill, INoTargetSkill { + private final PlaceholderInt duration; + private final PlaceholderString colorA; + private final PlaceholderString colorB; + + public VFXTintMechanic(MythicLineConfig mlc) { + this.duration = mlc.getPlaceholderInteger(new String[]{"duration", "d"}, 0, new String[0]); + this.colorA = mlc.getPlaceholderString(new String[]{"c", "color", "ca", "colora"}, "FFFFFF", new String[0]); + this.colorB = mlc.getPlaceholderString(new String[]{"cb", "colorb"}, "FFFFFF", new String[0]); + } + + public ThreadSafetyLevel getThreadSafetyLevel() { + return ThreadSafetyLevel.SYNC_ONLY; + } + + public SkillResult castAtEntity(SkillMetadata meta, AbstractEntity target) { + VFX vfx = ModelEngineAPI.getVFX(target.getBukkitEntity()); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + int duration = this.duration.get(meta, target); + Color colorA = MythicUtils.getColor(MythicUtils.getOrNull(this.colorA, meta, target)); + if (duration <= 0) { + vfx.setColor(colorA); + } else { + Color colorB = MythicUtils.getColor(MythicUtils.getOrNull(this.colorB, meta, target)); + new VFXTintMechanic.Animator(vfx, duration, colorA, colorB); + } + + return SkillResult.SUCCESS; + } + } + + public SkillResult cast(SkillMetadata meta) { + UUID uuid = MythicUtils.getVFXUniqueId(meta); + VFX vfx = ModelEngineAPI.getAPI().getVFXUpdater().getVFX(uuid); + if (vfx == null) { + return SkillResult.INVALID_TARGET; + } else { + int duration = this.duration.get(meta); + Color colorA = MythicUtils.getColor(MythicUtils.getOrNull(this.colorA, meta)); + if (duration <= 0) { + vfx.setColor(colorA); + } else { + Color colorB = MythicUtils.getColor(MythicUtils.getOrNull(this.colorB, meta)); + new VFXTintMechanic.Animator(vfx, duration, colorA, colorB); + } + + return SkillResult.SUCCESS; + } + } + + private static class Animator implements Runnable { + private final VFX target; + private final double duration; + private final VFXTintMechanic.FloatColor colorA; + private final VFXTintMechanic.FloatColor colorB; + private final PlatformTask task; + private double iteration; + + public Animator(VFX entity, int duration, Color colorA, Color colorB) { + this.duration = duration; + PlatformScheduler scheduler = ModelEngineAPI.getAPI().getScheduler(); + if (entity.getBase() instanceof BukkitEntity bukkitEntity) { + this.task = scheduler.scheduleRepeating(ModelEngineAPI.getAPI(), bukkitEntity.getOriginal(), this, 0L, 1L); + } else { + this.task = scheduler.scheduleRepeating(ModelEngineAPI.getAPI(), this, 0L, 1L); + } + + this.colorA = new VFXTintMechanic.FloatColor(colorA); + this.colorB = new VFXTintMechanic.FloatColor(colorB); + this.target = entity; + } + + @Override + public void run() { + if (this.iteration > this.duration) { + this.task.cancel(); + } else { + this.target.setColor(this.lerpColor(this.iteration / this.duration)); + this.iteration++; + } + } + + private Color lerpColor(double ratio) { + int r = (int)(Math.sqrt((1.0 - ratio) * this.colorA.r + ratio * this.colorB.r) * 255.0); + int g = (int)(Math.sqrt((1.0 - ratio) * this.colorA.g + ratio * this.colorB.g) * 255.0); + int b = (int)(Math.sqrt((1.0 - ratio) * this.colorA.b + ratio * this.colorB.b) * 255.0); + return Color.fromRGB(r, g, b); + } + } + + private static class FloatColor { + protected final float r; + protected final float g; + protected final float b; + + public FloatColor(Color color) { + this.r = color.getRed() * color.getRed() / 65025.0F; + this.g = color.getGreen() * color.getGreen() / 65025.0F; + this.b = color.getBlue() * color.getBlue() / 65025.0F; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/placeholders/CasterModelRotationPlaceholder.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/placeholders/CasterModelRotationPlaceholder.java new file mode 100644 index 0000000..b142904 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/placeholders/CasterModelRotationPlaceholder.java @@ -0,0 +1,31 @@ +package com.ticxo.modelengine.core21.mythic.placeholders; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import io.lumine.mythic.api.skills.SkillCaster; +import io.lumine.mythic.core.skills.placeholders.PlaceholderContext; +import io.lumine.mythic.core.skills.placeholders.types.GenericPlaceholder; +import io.lumine.mythic.core.skills.placeholders.types.GenericPlaceholder.GenericPlaceholderArguments; +import io.lumine.mythic.core.skills.placeholders.types.GenericPlaceholderTypes.StringPlaceholder; +import io.lumine.mythic.core.utils.annotations.MythicPlaceholder; + +@MythicPlaceholder( + placeholder = "caster.model.yaw" +) +public class CasterModelRotationPlaceholder extends GenericPlaceholder implements StringPlaceholder { + public CasterModelRotationPlaceholder(GenericPlaceholderArguments arguments) { + super(arguments); + } + + public String applyWithMetaKeywords(PlaceholderContext placeholderContext) { + SkillCaster caster = placeholderContext.meta().getCaster(); + ModeledEntity model = ModelEngineAPI.getModeledEntity(caster.getEntity().getUniqueId()); + if (model == null) { + return "[No Model]"; + } else { + BodyRotationController controller = model.getBase().getBodyRotationController(); + return String.valueOf(controller.getYBodyRot()); + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelDriverTargeter.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelDriverTargeter.java new file mode 100644 index 0000000..ce808c7 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelDriverTargeter.java @@ -0,0 +1,37 @@ +package com.ticxo.modelengine.core21.mythic.targeters; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.core21.mythic.utils.MythicTargeter; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.skills.SkillCaster; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.targeters.IEntityTargeter; +import io.lumine.mythic.bukkit.BukkitAdapter; +import java.util.Collection; +import java.util.HashSet; + +@MythicTargeter( + name = "modeldriver", + aliases = {} +) +public class ModelDriverTargeter implements IEntityTargeter { + public Collection getEntities(SkillMetadata skillMetadata) { + HashSet targets = new HashSet<>(); + SkillCaster caster = skillMetadata.getCaster(); + ModeledEntity model = ModelEngineAPI.getModeledEntity(caster.getEntity().getUniqueId()); + if (model == null) { + return targets; + } else { + BehaviorManager main = ((MountData)model.getMountData()).getMainMountManager(); + if (((MountManager)main).isControlled()) { + targets.add(BukkitAdapter.adapt(((MountManager)main).getDriver())); + } + + return targets; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelPartTargeter.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelPartTargeter.java new file mode 100644 index 0000000..47312ab --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelPartTargeter.java @@ -0,0 +1,102 @@ +package com.ticxo.modelengine.core21.mythic.targeters; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.utils.OffsetMode; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicTargeter; +import io.lumine.mythic.api.adapters.AbstractLocation; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.SkillCaster; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.placeholders.PlaceholderDouble; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.api.skills.targeters.ILocationTargeter; +import io.lumine.mythic.bukkit.BukkitAdapter; +import java.util.Collection; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map.Entry; +import org.joml.Vector3f; + +@MythicTargeter( + name = "modelpart", + aliases = {} +) +public class ModelPartTargeter implements ILocationTargeter { + private final PlaceholderString modelId; + private final PlaceholderString partId; + private final PlaceholderString offset; + private final boolean exactMatch; + private final boolean scale; + private PlaceholderDouble x; + private PlaceholderDouble y; + private PlaceholderDouble z; + + public ModelPartTargeter(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.partId = mlc.getPlaceholderString(new String[]{"p", "pid", "part", "partid"}, null, new String[0]); + this.offset = mlc.getPlaceholderString(new String[]{"o", "off", "offset"}, "LOCAL", new String[0]); + String coords = mlc.getString(new String[]{"location", "loc", "l", "coordinates", "c"}, null, new String[0]); + if (coords != null) { + String[] split = coords.split(","); + + try { + this.x = PlaceholderDouble.of(split[0]); + this.y = PlaceholderDouble.of(split[1]); + this.z = PlaceholderDouble.of(split[2]); + } catch (Exception var5) { + TLogger.error("The 'coordinates' attribute must be in the format c=x,y,z."); + this.x = PlaceholderDouble.of("0"); + this.y = PlaceholderDouble.of("0"); + this.z = PlaceholderDouble.of("0"); + } + } else { + this.x = mlc.getPlaceholderDouble("x", "0"); + this.y = mlc.getPlaceholderDouble("y", "0"); + this.z = mlc.getPlaceholderDouble("z", "0"); + } + + this.exactMatch = mlc.getBoolean(new String[]{"em", "exact", "match", "exactmatch"}, true); + this.scale = mlc.getBoolean(new String[]{"s", "sc", "scale"}, true); + } + + public Collection getLocations(SkillMetadata skillMetadata) { + HashSet targets = new HashSet<>(); + SkillCaster caster = skillMetadata.getCaster(); + ModeledEntity model = ModelEngineAPI.getModeledEntity(caster.getEntity().getUniqueId()); + if (model == null) { + return targets; + } else { + String modelId = MythicUtils.getOrNullLowercase(this.modelId, skillMetadata); + OffsetMode offsetMode = OffsetMode.get(this.offset.get(skillMetadata).toUpperCase(Locale.ENGLISH)); + Vector3f offset = new Vector3f().set(this.x.get(skillMetadata), this.y.get(skillMetadata), this.z.get(skillMetadata)); + model.getModel(modelId).ifPresentOrElse(activeModel -> { + String partId = MythicUtils.getOrNullLowercase(this.partId, skillMetadata); + if (this.exactMatch) { + activeModel.getBone(partId).ifPresent(modelBone -> targets.add(BukkitAdapter.adapt(modelBone.getLocation(offsetMode, offset, this.scale)))); + } else { + for (Entry entry : activeModel.getBones().entrySet()) { + if (entry.getKey().contains(partId)) { + targets.add(BukkitAdapter.adapt(entry.getValue().getLocation(offsetMode, offset, this.scale))); + } + } + } + }, () -> model.getModels().values().forEach(activeModel -> { + String partId = MythicUtils.getOrNullLowercase(this.partId, skillMetadata); + if (this.exactMatch) { + activeModel.getBone(partId).ifPresent(modelBone -> targets.add(BukkitAdapter.adapt(modelBone.getLocation(offsetMode, offset, this.scale)))); + } else { + for (Entry entry : activeModel.getBones().entrySet()) { + if (entry.getKey().contains(partId)) { + targets.add(BukkitAdapter.adapt(entry.getValue().getLocation(offsetMode, offset, this.scale))); + } + } + } + })); + return targets; + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelPassengersTargeter.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelPassengersTargeter.java new file mode 100644 index 0000000..e96786c --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/ModelPassengersTargeter.java @@ -0,0 +1,72 @@ +package com.ticxo.modelengine.core21.mythic.targeters; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.core21.mythic.MythicUtils; +import com.ticxo.modelengine.core21.mythic.utils.MythicTargeter; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.SkillCaster; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.placeholders.PlaceholderString; +import io.lumine.mythic.api.skills.targeters.IEntityTargeter; +import io.lumine.mythic.bukkit.BukkitAdapter; +import java.util.Collection; +import java.util.HashSet; +import org.bukkit.entity.Entity; + +@MythicTargeter( + name = "modelpassengers", + aliases = {} +) +public class ModelPassengersTargeter implements IEntityTargeter { + private final PlaceholderString modelId; + private final PlaceholderString pbone; + + public ModelPassengersTargeter(MythicLineConfig mlc) { + this.modelId = mlc.getPlaceholderString(new String[]{"m", "mid", "model", "modelid"}, null, new String[0]); + this.pbone = mlc.getPlaceholderString(new String[]{"p", "pbone", "seat"}, null, new String[0]); + } + + public Collection getEntities(SkillMetadata skillMetadata) { + HashSet targets = new HashSet<>(); + SkillCaster caster = skillMetadata.getCaster(); + ModeledEntity model = ModelEngineAPI.getModeledEntity(caster.getEntity().getUniqueId()); + if (model == null) { + return targets; + } else { + String parts = MythicUtils.getOrNullLowercase(this.pbone, skillMetadata); + if (parts == null) { + return targets; + } else { + String[] seats = parts.split(","); + String modelId = MythicUtils.getOrNullLowercase(this.modelId, skillMetadata); + model.getModel(modelId).ifPresentOrElse(activeModel -> activeModel.getMountManager().ifPresent(mountManager -> { + for (String seat : seats) { + ((MountManager)mountManager).getSeat(seat).ifPresent(mount -> { + for (Entity passenger : ((Mount)mount).getPassengers()) { + targets.add(BukkitAdapter.adapt(passenger)); + } + }); + } + }), () -> { + for (ActiveModel activeModel : model.getModels().values()) { + activeModel.getMountManager().ifPresent(mountManager -> { + for (String seat : seats) { + ((MountManager)mountManager).getSeat(seat).ifPresent(mount -> { + for (Entity passenger : ((Mount)mount).getPassengers()) { + targets.add(BukkitAdapter.adapt(passenger)); + } + }); + } + }); + } + }); + return targets; + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/MountedModelTargeter.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/MountedModelTargeter.java new file mode 100644 index 0000000..46ac9cc --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/targeters/MountedModelTargeter.java @@ -0,0 +1,34 @@ +package com.ticxo.modelengine.core21.mythic.targeters; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.core21.mythic.utils.MythicTargeter; +import io.lumine.mythic.api.adapters.AbstractEntity; +import io.lumine.mythic.api.skills.SkillCaster; +import io.lumine.mythic.api.skills.SkillMetadata; +import io.lumine.mythic.api.skills.targeters.IEntityTargeter; +import io.lumine.mythic.bukkit.BukkitAdapter; +import java.util.Collection; +import java.util.HashSet; +import org.bukkit.entity.Entity; + +@MythicTargeter( + name = "mountedmodel", + aliases = {} +) +public class MountedModelTargeter implements IEntityTargeter { + public Collection getEntities(SkillMetadata skillMetadata) { + HashSet targets = new HashSet<>(); + SkillCaster caster = skillMetadata.getCaster(); + ActiveModel model = ModelEngineAPI.getMountPairManager().getMountedPair(caster.getEntity().getUniqueId()); + if (model != null) { + BaseEntity base = model.getModeledEntity().getBase(); + if (base.getOriginal() instanceof Entity entity) { + targets.add(BukkitAdapter.adapt(entity)); + } + } + + return targets; + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/ModelEngineComponentRegistry.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/ModelEngineComponentRegistry.java new file mode 100644 index 0000000..00fc4e6 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/ModelEngineComponentRegistry.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.core21.mythic.utils; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.ModelEngineAPI; +import io.lumine.mythic.api.config.MythicLineConfig; +import io.lumine.mythic.api.skills.ISkillMechanic; +import io.lumine.mythic.api.skills.conditions.ISkillCondition; +import io.lumine.mythic.api.skills.targeters.ISkillTargeter; +import io.lumine.mythic.bukkit.MythicBukkit; +import io.lumine.mythic.bukkit.events.MythicConditionLoadEvent; +import io.lumine.mythic.bukkit.events.MythicMechanicLoadEvent; +import io.lumine.mythic.bukkit.events.MythicReloadedEvent; +import io.lumine.mythic.bukkit.events.MythicTargeterLoadEvent; +import io.lumine.mythic.bukkit.utils.Schedulers; +import io.lumine.mythic.core.logging.MythicLogger; +import io.lumine.mythic.core.skills.placeholders.Placeholder; +import io.lumine.mythic.core.utils.annotations.AnnotationUtil; +import io.lumine.mythic.core.utils.annotations.MythicPlaceholder; +import java.lang.reflect.Constructor; +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.plugin.java.JavaPlugin; + +public class ModelEngineComponentRegistry implements Listener { + private final Map> mechanics = Maps.newConcurrentMap(); + private final Map> conditions = Maps.newConcurrentMap(); + private final Map> targeters = Maps.newConcurrentMap(); + private final Map> placeholders = Maps.newConcurrentMap(); + + public ModelEngineComponentRegistry(JavaPlugin plugin, String packagePath) { + this(plugin, Lists.newArrayList(new String[]{packagePath})); + } + + public ModelEngineComponentRegistry(JavaPlugin plugin, Collection packages) { + for (String packagePath : packages) { + for (Class clazz : AnnotationUtil.getAnnotatedClasses(plugin, packagePath, MythicMechanic.class)) { + try { + MythicMechanic annotation = clazz.getAnnotation(MythicMechanic.class); + String namespace = annotation.namespace(); + String name = annotation.name(); + String[] aliases = annotation.aliases(); + if (ISkillMechanic.class.isAssignableFrom(clazz)) { + Constructor constructor; + try { + constructor = (Constructor)clazz.getConstructor(MythicLineConfig.class); + } catch (NoSuchMethodException var20) { + try { + constructor = (Constructor)clazz.getConstructor(MythicMechanicLoadEvent.class); + } catch (NoSuchMethodException var19) { + constructor = (Constructor)clazz.getConstructor(); + } + } + + this.mechanics.put(name.toUpperCase(), constructor); + this.mechanics.put(namespace.toUpperCase() + ":" + name.toUpperCase(), constructor); + + for (String alias : aliases) { + this.mechanics.put(alias.toUpperCase(), constructor); + this.mechanics.put(namespace.toUpperCase() + ":" + alias.toUpperCase(), constructor); + } + } + } catch (Throwable var24) { + MythicLogger.error("Failed to register custom mechanic {0}", new Object[]{clazz.getCanonicalName()}); + var24.printStackTrace(); + } + } + + for (Class clazz : AnnotationUtil.getAnnotatedClasses(plugin, packagePath, MythicCondition.class)) { + try { + MythicCondition annotation = clazz.getAnnotation(MythicCondition.class); + String namespace = annotation.namespace(); + String name = annotation.name(); + String[] aliases = annotation.aliases(); + if (ISkillCondition.class.isAssignableFrom(clazz)) { + Constructor constructor; + try { + constructor = (Constructor)clazz.getConstructor(ModelEngineAPI.class, MythicConditionLoadEvent.class); + } catch (NoSuchMethodException var23) { + try { + constructor = (Constructor)clazz.getConstructor(MythicLineConfig.class); + } catch (NoSuchMethodException var22) { + constructor = (Constructor)clazz.getConstructor(); + } + } + + this.conditions.put(name.toUpperCase(), constructor); + this.conditions.put(namespace.toUpperCase() + ":" + name.toUpperCase(), constructor); + + for (String alias : aliases) { + this.conditions.put(alias.toUpperCase(), constructor); + this.conditions.put(namespace.toUpperCase() + ":" + alias.toUpperCase(), constructor); + } + } + } catch (Throwable var25) { + MythicLogger.error("Failed to register custom condition {0}", new Object[]{clazz.getCanonicalName()}); + var25.printStackTrace(); + } + } + + for (Class clazz : AnnotationUtil.getAnnotatedClasses(plugin, packagePath, MythicTargeter.class)) { + try { + MythicTargeter annotation = clazz.getAnnotation(MythicTargeter.class); + String namespace = annotation.namespace(); + String name = annotation.name(); + String[] aliases = annotation.aliases(); + if (ISkillTargeter.class.isAssignableFrom(clazz)) { + Constructor constructor; + try { + constructor = (Constructor)clazz.getConstructor(MythicLineConfig.class); + } catch (NoSuchMethodException var21) { + constructor = (Constructor)clazz.getConstructor(); + } + + this.targeters.put(name.toUpperCase(), constructor); + this.targeters.put(namespace.toUpperCase() + ":" + name.toUpperCase(), constructor); + + for (String alias : aliases) { + this.targeters.put(alias.toUpperCase(), constructor); + this.targeters.put(namespace.toUpperCase() + ":" + alias.toUpperCase(), constructor); + } + } + } catch (Throwable var26) { + MythicLogger.error("Failed to register custom targeter {0}", new Object[]{clazz.getCanonicalName()}); + var26.printStackTrace(); + } + } + + for (Class clazz : AnnotationUtil.getAnnotatedClasses(plugin, packagePath, MythicPlaceholder.class)) { + try { + MythicPlaceholder anno = clazz.getAnnotation(MythicPlaceholder.class); + String name = anno.placeholder(); + String[] aliases = anno.aliases(); + if (Placeholder.class.isAssignableFrom(clazz)) { + this.placeholders.put(name, (Class)clazz); + + for (String alias : aliases) { + this.placeholders.put(alias, (Class)clazz); + } + } + } catch (Exception var27) { + MythicLogger.error("Failed to load placeholder {0}", new Object[]{clazz.getCanonicalName()}); + } + } + } + + Schedulers.sync().runLater(() -> this.injectPlaceholders(), 20L); + } + + @EventHandler + public void onMythicMechanicLoad(MythicMechanicLoadEvent event) { + String name = event.getMechanicName().toUpperCase(); + if (this.mechanics.containsKey(name)) { + Constructor constructor = this.mechanics.get(name); + + try { + if (constructor.getParameterCount() == 1) { + if (constructor.getParameterTypes()[0] == MythicLineConfig.class) { + event.register(constructor.newInstance(event.getConfig())); + } else { + event.register(constructor.newInstance(event)); + } + } else { + event.register(constructor.newInstance()); + } + } catch (Exception var5) { + MythicLogger.error("Failed to construct mechanic {0}", new Object[]{name}); + var5.printStackTrace(); + } + } + } + + @EventHandler + public void onMythicConditionLoad(MythicConditionLoadEvent event) { + String name = event.getConditionName().toUpperCase(); + if (this.conditions.containsKey(name)) { + Constructor constructor = this.conditions.get(name); + + try { + if (constructor.getParameterCount() == 2) { + event.register(constructor.newInstance(ModelEngineAPI.getAPI(), event)); + } else if (constructor.getParameterCount() == 1) { + event.register(constructor.newInstance(event.getConfig())); + } else { + event.register(constructor.newInstance()); + } + } catch (Exception var5) { + MythicLogger.error("Failed to construct condition {0}", new Object[]{name}); + var5.printStackTrace(); + } + } + } + + @EventHandler + public void onMythicTargeterLoad(MythicTargeterLoadEvent event) { + String name = event.getTargeterName().toUpperCase(); + if (this.targeters.containsKey(name)) { + Constructor constructor = this.targeters.get(name); + + try { + if (constructor.getParameterCount() == 1) { + event.register(constructor.newInstance(event.getConfig())); + } else { + event.register(constructor.newInstance()); + } + } catch (Exception var5) { + MythicLogger.error("Failed to construct targeter {0}", new Object[]{name}); + var5.printStackTrace(); + } + } + } + + @EventHandler + public void onMythicReloaded(MythicReloadedEvent event) { + this.injectPlaceholders(); + } + + private void injectPlaceholders() { + for (Entry> entry : this.placeholders.entrySet()) { + String name = entry.getKey(); + Class clazz = (Class)entry.getValue(); + + try { + MythicBukkit.inst().getPlaceholderManager().register(clazz); + } catch (Exception var6) { + MythicBukkit.inst().getPlaceholderManager().register(name, clazz); + } + } + } +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicCondition.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicCondition.java new file mode 100644 index 0000000..1e7b4bb --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicCondition.java @@ -0,0 +1,21 @@ +package com.ticxo.modelengine.core21.mythic.utils; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface MythicCondition { + String name() default ""; + + String[] aliases() default {}; + + String author() default ""; + + String description() default ""; + + String version() default "4.0"; + + boolean premium() default false; + + String namespace() default "meg"; +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicMechanic.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicMechanic.java new file mode 100644 index 0000000..a9d899d --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicMechanic.java @@ -0,0 +1,21 @@ +package com.ticxo.modelengine.core21.mythic.utils; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface MythicMechanic { + String name() default ""; + + String[] aliases() default {}; + + String author() default ""; + + String description() default ""; + + String version() default "4.0"; + + boolean premium() default false; + + String namespace() default "meg"; +} diff --git a/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicTargeter.java b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicTargeter.java new file mode 100644 index 0000000..2e7fa78 --- /dev/null +++ b/core21/src/main/java/com/ticxo/modelengine/core21/mythic/utils/MythicTargeter.java @@ -0,0 +1,21 @@ +package com.ticxo.modelengine.core21.mythic.utils; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface MythicTargeter { + String name() default ""; + + String[] aliases() default {}; + + String author() default ""; + + String description() default ""; + + String version() default "4.0"; + + boolean premium() default false; + + String namespace() default "meg"; +} diff --git a/core25/build.gradle.kts b/core25/build.gradle.kts new file mode 100644 index 0000000..b9c0d93 --- /dev/null +++ b/core25/build.gradle.kts @@ -0,0 +1,4 @@ +dependencies { + compileOnly(project(":api")) + listOf("v26_1", "v26_2", "v26_3").forEach { compileOnly(project(":nms:$it")) } +} diff --git a/core25/src/main/java/com/ticxo/modelengine/core25/Java25Helper.java b/core25/src/main/java/com/ticxo/modelengine/core25/Java25Helper.java new file mode 100644 index 0000000..f1f114c --- /dev/null +++ b/core25/src/main/java/com/ticxo/modelengine/core25/Java25Helper.java @@ -0,0 +1,17 @@ +package com.ticxo.modelengine.core25; + +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.v26_1.NMSHandler_v26_1; +import com.ticxo.modelengine.v26_2.NMSHandler_v26_2; +import com.ticxo.modelengine.v26_3.NMSHandler_v26_3; + +public class Java25Helper { + public static NMSHandler createNMSHandler(String version) { + return (NMSHandler)(switch (version) { + case "26.1", "26.1.1", "26.1.2" -> new NMSHandler_v26_1(); + case "26.2", "26.2.1", "26.2.2" -> new NMSHandler_v26_2(); + case "26.3", "26.3.1", "26.3.2" -> new NMSHandler_v26_3(); + default -> null; + }); + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..629994b --- /dev/null +++ b/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx4g +org.gradle.parallel=true +org.gradle.caching=true +# Compile against the patched server jar only. Generating patched Minecraft +# sources for IDE browsing fails for the 1.19.4-1.20.2 dev bundles. +paperweight.experimental.genSources=false diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..51cbd2a6f8121b2ce12daf979b128058fb9672ee GIT binary patch literal 49154 zcma&OV|1nKwk@2bVmq0!ZQHhO+h)bKZB(38Y}=`zV%v6Zt-Wr$-@W^sv%dYdHs4?K z&oiDrdLMm^F{gs`H&9d{NJvN^ARxj&pa1Vc1cCyR6;%hzs2^rks%InQpN&4@i?cFB(v z-M(*+9p)GpVFh0|Q&|H$3~7y1>nj^sp)F4KdOQ7ZYY$i0^%@)D?(UUY2Oqa~O-NT) zOS^{7+TjluBM%!>1Kd73v)b$vQy*S0ci;F3fwv}yVk%tAAQYyj^gV6OK1G;!9vdu0 zDox12IZpCz&VtXW6fgH&Xl@*LM0Yw;+=3R@kn&(oL_)MHq-^4h ziloqQ;YM4`)-Q$-`hQ&u4tSU1XfMK*c>%mjH7s9?7CSx&CJU6+zDw09Aczx=7}{5T zB3v9D=x8yX9}pNU69oA*hV2VXuv3BigbBWK56c~ZWUH+)B{KHrxsxO32F zPxY?VAcXf89f7!7=uR{_O69bOCX06}5kzr{TRX!eU2F%pejHDwcs+e<@oy`=fK3mB z!v~EC!tOmi{^pRRN+$uDpuHG?Bn4NKEirR1L-#ch&FlzfeZ$V(G2I3KHA@!Pj-{B2 z=IP@Bd@ODoJsQuXt9tj z*|A7$pyJSQH)T$wB!Ch%2cJ7u+q>KrH$UC^zH?w9>>vfUgwQ4)*oo;^0QsVSwqbE{ zwVf(vdhOWq!5-Y-cG|#w%j__+qTu&ysquQmiJp6wiv&_c^ypd^01}zY@@Y(4Y;YIf zYUCwAzqg+r&(<{@%v7Ase+W+mJPi~_4lz9kBlkLbe4zk;WLHT=JLGVFXY9}Pcn6@s z*(S7<;RsGhRT6OD!DIwparxA!t^$(4E3w;ehI+}{Q3|k#1lEwkmtxu#5@2We)`_zd zLkmW4%~Xj4UPWtCkYA1A2nL}b-*91Qt^qjTs1>KaBk<^t2*T8)0yZRMl9;M}sbz0d_ERfsXTIYPt|* z)<8ts6N!-`35%l^znDvAxyFBuon0Z0`^NMf-z?ySQ)XRYz#XH|{hBX_fX;djHfp_< zA(3FR!PWxv_m_Jil8yvc-0EGD{cg){2h7dm0lFzTCz_e$#fN4=+<(KYh14l?a5-d^ zfPyAsx{9~wTiKh=n!f9Kd+WNWH@TZ(riZ@#202kD!5aU42?!J8IHcN!A{HKf*;RyZ zcv@TE0DWIfeN4fktgpm`@U3HaNC~x`dh6RKX$}yQYfuz+elh_qwPpfzTM@R(nG|U&;*q z_f>>=I}|m`2Nq%wV{1}xfPxt^H&lu=C$D9sM`4P>xY0TcVx&H+W)N@bgrid*x7>d6 zcP>0`lWh!2c{_o@kw+8ddI-~I=v^p^A|euqk~?1|WUhxJ$eV@j<`Q6U=QgqatP=ch zb1lv{F!NOFkGed525LskPL2=tUiBGc^EBe7V5&+c;K-1K`ONhkyI=zFJITG*Uaa3u zg`R=$Sr-L~myczhGI_4H2cK_P>+m`ThR1MBnQ`=&)%wWc1~2E5A@|J}*Pr}b4Ud}* z!1gub9DPDvpr+p(VXXTi5zBpv31|0EW;3L#i^y{|_I#=~{>ni>+Y&Zn--!oE=_ z#;>;{v2%~=9ThJo=QM%cL*d5E7d#$B_#f01z_I1rq9JV~U`m=iG@iQ%av-|5cCQA$ z%G{QYztF-TM=G2h8fg}N8Po3r{a`39QU>obM%$O$&4b$a+4D<*R@+}%;&{r04IQDF z3V)B_4>~Hb*zb$+>Mdfk8W9DeK~I*?-Uda}2jQrIs%pKfc1u(yJHi>L59HS}svrpc zvBHA<%@lg7d?tC;q8R6nl)jFt20p#;xC@bb9;{!jZvfF}uAKnxZ7{N6yQ58`(uawq ztXkVsX4EZG=z9>CLlzWXSMTj8sRXv+Pb7iZT}S}j`_^D2k8M_4Fn^GVs8z@)0cE3B z$;w2NWj^`tD_-5%h=O_TK5L#!u*6zHcRAh@_O=?FxXA4I5BqcYo1^pm#M1#w@*9+t zxw<2^wIm4k2q|OykPmJISDH}7MuheOj-AUn(>3D3p?I;3mG-Mq%*X>7cenDI>L{3}EHRWf zxQ@vi1gliTBw|r8zRft7o$cr*5fUZuq*qZUR#}78Sor0;7gm#7eR-L7WoI7mBmeC; z_QLd4Kr;6l`AiKg2%X7zhUu7oM)|Cl)OA5s`G|~Q8C@otpyX~gJIbD5Ond->kT^y6 za7{+~1bVlHIy77S9K}gp&Uo3qpX9h2fmq#1oS-bgMW$H}JyRsbTQMxpi6IYEGk19b zIC<8!A3&4Qp#nT}fUTXatqER}Cfnv?@6adpAX$nS@Etxr2Moma0Sm!1y8Fa|4+4%E z8HTg~s%y&`BlOwT?r?HT1g|wER+#UYQ0Xob*0dsahE}L*&x8$sBD9L?eZ#0HN!)~t zwEU9xo;5?E?g5vBh#%!anPan@YEjh~+v1GG2&B&83uE0g($Zv`VGxK}M}{m@O>kzA zr#H6jW+c?}a&xyZLP=e)F(vdt21pKEKZ9B!oL{_#DR!TwVF_xYt9N_B;;KIdDQfI8 zQpQ&>i>O3ac53$~LyaVFdPs%Hv(=StN*X$QLru2A!DNF&nv5#Okp(a@D0fhdlFqU3 zZRPeZ3-nYG0oLB;ahxB?<&^0a7$X&PK`%K;C$a0Z=P^$7(@>3V*vri&C7timgKN~V zqGhUV=1bc8&=UPe1{iFV!Kqfrnz&vM(>J=v7Iqc==FluAnKj%dcMUNKR(2syhYBSh zq+rYVwn6*B^FWAVgP|4Vi~O>pUjA3uf>;^eA51|WAe$D5m2UI5UGtV#J69l|;0lu=f(ZgBOa_IT5y zSMm??r&VI-b7$Ir&vW29otI?UkxGe?R0f~RRsqlE5=xRTEesva6{f+w^Yi@LX$GpS z)uUIxTAo;>Z|T{pxrDiSyLjEG%|F;ZItV-Xz(*CjN_(nYgY)+_*fI6dsp>OCz(=>f zxiS2>v2&hSOtpu>?$iYO@Lo|_sQ$Jw>7dR5hjE?F+O;S#bJEKyg3&E>lZMEim3G@W z$GI)yu@1DniqycZe7Zu$T>j>*mN|TgQGGN;GqTBlc+HuPis3u!REgcrqi=M8Cg9&5 zaBl#(E-x@7KZeY4W3z%{*F+Q$=3_ekRWsMyE#;~^xOQp8G#-R zwHtC6o!+Yg@8qNTfinqO|y@AtSZlvRVOQ-t;<-Z@nCvF-tjay z^T48yk;B7oj>jx?+y*B6N)F?qAp6VtH8ZN|!V_{?@F_2$yuEym#^Cf(vgKjn7RxZQZPsJ*>Q-@A>t8&x<&9 zD7$J*SkdPhP;y5__KhyGZrI42Ej{Q3gf;%r0+|NM_oSssc8bV_Ws-{M;C^J$yh$~H zJjNZ)tuZ#&M%fZ83v~}LhP~7NW1ZF1c#8Nli=pJ{qNbDPN%>gdqyp*@vy`y%p_g?J z?|Tzs+~aU`3APxM&v;Q|G3+8boZgm7?5fJNZt$nm9tCL#$hwvyyc0Mepl)&?AcgzQ5_8J(v>y2ENiG+cWHyOJ;b8uW zz4)YZqH_R`YraE9{5<ePTBdC<>YrPjp<>p9ec?P00Q%m<0rl!(T0Yi-P>yDVjqTIHWYcQ z1fZaIRkx9LjfB7(lVyshjBKcsMMaWkwCx@hxVkTm4g2F~5TY-KUFa;JIGcOW#6fg1 zW+~K7CH{WO0(U~(x_ZzY9GRb@MG>hM4rBf5`4edfNZKPW5#&EnSO3Szll^1l<^Q{In<{C`qX?pYhNjZl zrb$nTUI(`7SrnKm3Q%L}LsCfs8$*HaO}MzP!k?G?-Y6WF*qyn?c&IXOl=EWd_xbXQ+e?Fvxp{HHOWieBvA%*7`(w&lOqSXr)SA6y=-UaG z=o%~7BCjFTB@CC1LyrYZaQ$A3jeb_G;{*m+wI=;)r)DzJNaJ>srkqBt%e=m|COVp1 z$Po%Pnv}A$GPCpQ8XZHZ%8;#Rs0RscAH$)SYuBaY0&=^dr0-ml?Pa>@NqCbPM^Ye% z@D|(FLHkfnd$-yKx>!CzUw$i6zxgq}_;)n|+7GBFY&4`>%0m>KcfDYS9|d;^1P(Zpefo9hSS0F z$lSeQMy#hsM@~e%S}mb~;aSoF8VBCc0-bK#*#rLvFf?`t=9sfq*M6r%9l_Z3k`{fm z+Q4J28C4krrWhV*mTZ(12)Wj^&5-o6{IJ#&=32M&(m?LPVc8@@2KR1um5d=Bi&tb=JSf{LTDzFP$7LDIiw6JB$$mzH?)mLbD^2S?A1AO z>xhOl2?DXVy|IXD42a{e(7x(#uouS9C^hGMr(f@@gu{UGq%aDm&XG}2(H4N8f!P6b zD2%>?{oTM^ZJfwrz+0o)oMW(~3&pX@DCGMv#o>=!f*lVQ5t{ztPmsUR%rg^Q?Fa${ zl>P0Wc!c>M(X3$Thw3Vo&SwVQj~T7f;R60dMaH>3DI+PYv5y2CZuG^ zFsP)DRd2Y_cvQxv+{FCGZ!MAQ~b8I}4wm6Q>YGV^gv5sr5GLv_&TAxob_hcq_Ry9l4~VwZX)#^cK!pZ>G-L z>A3tZzQ%1sxcbS_b{*%pcE2y3c~Co>MxiPz$Zx7=9Y^b_ljW=S%jsxnd9;}LVgneD zvGvMjZr0sEg?}qwNNGDxAfYYPQ&;AmIaw~+QtCMzz_7N=LkDYJJ>I`yA;Xpw5Y9Cq zT?<%Xnqsnl31UXS0s{HgxkQzXF@24sxjn`i^047&?3o6gU#3u9id`(yB@AK5NW|g| z(_LQll;g3`L`DqKrx)Fy>1sK2nyIk^8caJ_0TUSn81N>#6bP0JuhaSs1hGT-qntHz3%NDqb&CUp-x2--EXfJ&H}OA!%>w-= z!1DYjfE6+|vv)ETvvhKHQFb-@-@^EB$Zb-!RbJ3Q^`j%8tS?91a(A^p*RsH_xFu5X z0Y*iIX^o;+9swM&b=eYI&Pysenww|*&a2;gf~ez$W_B}s$YTC1ca={p6i9eBElVnX zT0hEuTX)WLz8vx2`ut`9%Fp=T-Tis@Tq~7eUD;1VnG~s}#uRC`c-r2lyTP=WsfujU z5<=KYY|$`|t6B+dyJ-0f$FyM*PTVBfOSJl?z2c3L4n_}eC%9>(jfk?Bk_2u zti_t6I@ZuqXE0r;bwT%ptG)Ju^}3y=n$9IO)CTN^ovJ%>8X(z6BORxp%thJVo?#Lp zc;Jc1$Jr8sj{TV<64J}d0dkJQ1Sgen2U57!6j^u;&V!i;ceH1l-g9Z&jI?8SwOw

D4ii5U)8pSQ%EF)}Pk=FpU6G*dMWV z=Tz*G&b=b4GdF4%cKUIfrQ7(}IxE#7w%{j`PN+0@1RaJxIeV8hTrzUUb#jmJzfG-7t}@^-6aQZRI272}=n)<#_!)zZXE zLXawGEbW%d%s>9BQHKP70+ORnL^8DQ#Oum|ZFtUJP@( zNeRWCRFIWIjt5bk2hfK(5aHX5seqNn7ztIOrdO*RMjR0~YOws8Jc3i&iMR~lN)$#~ zUq{(-?!rYiT#aHFKy<9OrNqa#a3?&sUB9VwW(wt9+POIYR2OlM+nKrUZmi5k;JO8R z;vYNgjt1KYw40sOQs_5OKZ zkz$d~O7atAQWbCIv*-NopX=e_Nj=$+-IDWqb%@UG-LsEe5Z$t>i1_SJJaW8c_0r#a zncLZ@CTeOEV{60i#75glbN;kG;(9iyyZ4AmGq+`7A8n8lc zIr+}(mVd|pS61t0B%~Vuk)TJcQ>tmbX`<)F80X%wx^RxmH(eKx!_!5(^50cH&OnB_@5 zDWDAg%J?o?`v9{GUW2?kE2{yattuS@Awrw$t#rEawo5?zHR|%7bWYA%| zI^=w$HHw#YZ{MnCAs(1b<&eg)A216Q#RC$4_HXv`9`$lOo!rOKUMHS6#kQ1=p&eyv zoR+ViI=I#Mf+y*%UBZ;IhC1Zawj$TE>I)lfGL$oB@8Q@z6jmbs8LD`F>2^o2*5OrL@YXt zoJ}oeI4-tu+{pAo!;TY*JC$qIZe_CS)1r-z1!BsVL!u+ZS^ipfnKP=GFKi0oeo|p; zpE?(v%Edz1U$;NG%cm?Y9nJ{)NcMD|JVzD1YhkRxmDL_BO}WX%&NLlPy>ACdGZscn zGbHY+JYgx3Y#Z?v4)YlQz22ZdjAnt6sCNP_g17HNckAeT2XYW!56})Ic~A>I_P?SD zF*w>mePV5o-0A#{cQI=1m8p%)1z6>V3o&<|4pvf90;t=Pnr9emWtOEFE-1bCN1eF@ z?=Du&t3=gk`lS(FkgZM=xEWwTl^r_$A_MF?ORChbm5IUYM{R)Ya)nluE@_dN5l$8_ zei7b72lIt$jnKIMFr7-#9)0v$C$M=7TA|aRzsg)QtteKNm0I0zHcF4(Eickhi~*d4 zAIT=06)vexoE(JVMnVP^|K<)Ew0l%gTaOk@Kx<*J$z+G|Vp$`L)Eh_1-10+EnBhO0 zzPmCbC@cbZL=+Zb9mug(?MP-90!e*nl5+c=hfk*6V1i@p zDdLd&!)2!Hdix>7-+<<#y2&eYFr{Y9z*!W|u_YtrqvD<%^*;i5sBbShtsc-Oko6#U zMf+?|&Xq|zWj+-fI?_M_zM>>gNjN=J)7IpBx`%P$fp&B+=w$7`~QBQ$l=hO$Mp%x>T@iP{KRJsDp_6xO$-)@NrXljrnLj5%h39>gW190b>FNR_#T zaMZfe@5dM#UwF-;Q7bO61riMc-$h+uQR^>$DzD^{R4#6m)e&=Iaw_;gpw>_pdgphS zh4Y#;xI?r1DI2mXG)Sdt&PAv`4<4vIkoTYI_&v~Z_ti(@RFOe}47&0+KkIl~#oF^-lwFaR=yPJf2yb323DD(SqFvY?VnG!hIG7Be0j+ZS*KY$(Lig2@pn zeB8h$l8lBnds~59HUy(1tG9)zs0s%ZZ`WZ@B!rr2Y@$jgifj}s1TKY0@G5VES&VI7 zDPTmwBoK{Zp6pYuphS=s)xX+EiY_QS&Io+intCC>ixO#7!qkD;-3uV0j0L-&=4ivT zX5m%BgHxpWYCSyV_7)~t{0LwEa28$s=G996NQ!5!A{V2G#XEIP```-_7lp&g`SCOC z!v~3;w6NQh2>F3F%PZWZ_WJrE0A!P-2zmV;;ReteD*$}O0v^fXX!Ba;0gNAh69)Q8 z9H8$*RPVTc4N%V==7JKJ6HdH7#&5l531oSOu|Clk`g9*$ zN4y+~j11P6elt!^&9W#>iX@hQ;1ulRlQQ&8thiIHnAtP&3_QKVsF>ELeC|;^{fq!_ zhMri#YPYF%cdXQ{S^WA}LjuOZDQy%S2*@1%pS1Hos)%JRot-W1%>P!;KkcFaPC9dv zbnO=yP($@wv=_`Mtzp21mkDfUujFP0n+OqQ98}pv<`6ram0Mt>v#BJ>2?t3&5in!| zi5&Y7w#5nM8c=P^=lP7r+_H~+%%9H2PSFdQ=oFGh(UwNcK=L3y-mE_3us zwy{#eh@o&b`pa%LsIm!OcUrOR4D^Ov*MB*HsRxmq!7|6{xbHu=zMLRG5lf>*u5osMeRny* zW+GmvQWtCeKl0#Ondo%z1+a`vZ!J5 z;p5v+`l{UNtYN4L>MAr9VktK@XwJc19-C6zrNRX6D`5t%1txc_$69v?t+iB^R@0%j z8AhdRQ4Y!KMVzt5O7=x9WY;-e&Ub6D!Xo29TB1-x9U?PF`~W;8VMO=!Xx2!{cFzCt zYTBtKCX%;-go&92Jyju!N9RZ!RAcY*u}|iez$WvDok^cc25Q9g=r6Hcf@tV^v2QQb2&uyp}1WE z-#-@+pnk{TQ(qXFHNGwC%;zaluEiJ-;OH7b@R;9Lqij2o*r1{n+hnHLLE}c27wKx1 zbz3Hc4uvvu3TwB6UlO(%z*EHo1oUE|{p*x}1#S{_3;}ed-jTD2RiF|{Mo+Z~0 zkf=Py*QvojtsJr%&SAu{3ag+Z46vB}WOg`(J5B4AMQ^q2)2j_)4LdDK?D1NG(BIP` zT+4k^@K}UrRZT0*^hR-Jumf}TAY=({F@l@mRBN4v9@FkG+&xh21E4?eox zqxL!956jJc!ChkX1A)_jM+mQoaU)&jb_w;?KOU`jRV1Yo7L-({CeZ*g!0XqP+`yd!BEbfI@d^uYDIB z`*RyEJxmd$f|LR~(4BBh_F_om-4W|(>`hkB7DwbkIrC_$Qd#m_Y+y0C3`-l7*sRg6 z(vK;8aw$dzLX@9W-!7_`mh2`xDFP4`@PZ?5jy0%|>rk+^9^hh8+j0{x6){1}#d&|6 zz{<*)U9d=1`=Wh|N{x)iQ0VA`YKLyR%7wQd{V7TTNpUVod(r(}$M?etUW!3ElqeZY zMQBRL_|3%}A)4NxqkHqs`M$P5_Yv2slnmICdb@7(&5@x_%&Oj-q9r0Me&>;rysH71BQ_P2Ojb&J#PF1OUvZ)q#bQjCKL zd}8A~7(Z<6W^beckqf^6K@B|hs`jyy`bY;h9BC{)p{6){$y~nfiOh z)i#TJgLeT5Lg!Ve=E|F}NsU0Ztd^j!&SOyCV_;XVr+$kQ`Ol1D4DqO8CVuM;7boqU zfn=i`j5AJV1Qw4udHkp6Pl<#0)l}**Dmvn%&_HS`B@K;UQkn{hxGo-HDu)p?Sm}dt z9&koo`JGe!Uu78WVu8=VX#rp3u;8#0&gH6ll^T69EH!&%!Z%ybNd=a!Au0}U{0Dz@ zptwG=g9PM>2a8{lpWYQblVwY>KJ=k(h!;&-1HKFSTamXaCUOUhN2m=)^U)tM-k08l z8p*N*yI;+9q+cZ#52U=uG2Tx|+&>V)B@RXsPdNv_kP2S_X;^f71Nj}}yl-_x;X@W) zAjT&7#o^l)KT$j?5Xh6S$tz5!kF&D`QROpa)$vNE-}&7wv>)-$Q`{rM{sLSMTCrQsr?K{h1uE$hMc4^Y;f~Ug3}oG%eXToN z@%-W9isy}9Oa?-EFSA8qu@fOa~?)OmKXQ_rnnu|D<}(J zOW%7eriLK8KwmSBU0R7k-S7#0A?JhCFwB}U=(8lH5atR2D>vzejsjSpXcuM=b>=bo z=0dJfrhop+CwxZ=x$*x)G?D*EH2nX`J*(PT|3_UmW!pbvA4I>@X4G*_ngdy|A(SRs z+c*jlP~$+7;X&|dRhfv0-uK7ss`9WN4pXDqJJlRn*TGldBq$z@?xb{as>w9{VAJmOeqrAnpNb3B3Jd|TRZ?TWh;V^;CN zsRZXilpF-$-3RM`KQotjE|^fLxhFXetYH{zWdVp$ar?wsv$@MwV@XV~QnD8383KOY zO(Mn34avuUlBZgO$pb_#{f9R}(@^rZNM73BO9NSIO5;Vu1fhk4BnT=6`ch`Gl^MSG z&1M-$WD$AveW+SCQ6|a)q8w(ZHhs+$&c-9qF7Nt^NN5v|Mn_=O;~LyYfM&L6d`ya&%j#p*xdK`+ z0sQWMb|)z83HTvLw=hNuE#B%nD><|6rrv(#}BqSLA@$D}W-T3LEZ1xA&t^a5({&^_>H+lV=Zu+WftD~r+ ze#Sz{h1W}6&ub*dTcLmus?`yBL?Kb5AyZMr7%dF!$4ASU?M{m1>uK4332arw`QDUR zKNP|>*OpY>(hxs@N`XJOFJ9 zX5m9PFaYtpNsPONHn05p?X8^BLAg<$dbOpYNqWn^m&516aK0r(26n|n@lcZwLTW@@ zD_mjCywX-O2#nL`?S~`A0)(Gw%8)}Mud5S^QjeWgZ@cl$HAM0Wx5AP`hxvTMD8TUQ zH2)Nrks?JRUpz9aIFroB!(VpqR~O}R349~29p_{5Ve*nAs}NDm-gB?~(;;Yt;vu{) zNK}D4E1T}_QfsR&S|}A;f=Q!aI00z6kdhyUDIy0{ z4~eo#ggCMy8+ksBBVjbUs3SHyGraXNmt$8WtwbNOZwaY4_`i>JsCJh4dBh*m=)&Ky z9L?2>UxJGxLRq=WwF5EG`@tB6r!)u%Vj`Dhy)^oMVVi5ZwW;K>Y0X~*B%9uVweRLh z7F-}rxl!!0su$0#Rklm_Q_NYG`#C6BY8jtxEm?EyiQ^R~8?g=ldQD)XBS{L?o(j(1 zV5mNB3S^=zQsiwlo(EgO(8e9VZpe|4QF&)@$RcdL=>l=8nQb8@&%3QH18O2rX)6j-cEU3plH* zQ7Y5Q!%Q^ghlr&K>C4dzIVA#j2s?EqmWayPy_$MVYE&dGGZYe96cA^L2Iw+K#YctYO(y?8HCKF$V`FV1)Aucfx;y>mJtx{f6RN6>0A2 z(93zu=3IHi?T&HBcW#@j!9a|n;0@CYVx51W zKE%Y^6UbI`2Yd?XhxW_4EME`pFO>MV`xg&3?-26N2)b!<~aKRsj($bi&F1q;#n#@hsh`Ba32QdPcJNk}xR^vG)I zM^YLaw}DIWzSZ1Uh|XpHS#2JOf>BN_`_AiUh|YU+j{?WdsZu!EX~i)^bEb@prwq@- zoR5bqd_PczXmVJ6USBT$M~+4!bGFu+;9=p6MFo~*Mki0zB-_PVV@}~66ZW=Y)2M|w z>jt!ms+-AB)ltoY8&%Dp9xTZ-!%j|orCgkJj-IX>WctokI6YdkEKD|z3x!oCnAkV~ z94shaOHku$T1+tJ0s9Ipb4V;Rwp>4K(&4MI(xDVe;O~q4*jDrzn1o=18pn3Qg>A59cfl7(0gdLt$#XwQVCmc?xQbXv?Y2s zt%0Jd8(5Cxb2 z>Mg`4pFIo;1`^grlY=VrwGi)(6Jud5z%#Gtq{s-S!=Hwx$IlE|*7kdrUR_gBhx0%V z|P2f<*Zi`^-RsG#jwfE zCRk#aATa283)auMq!0IVRq1D{bt|2Qcix|77=sO80ku1vs(GstClm@bI-JsQE)z@4 zF63Ih4XFU=(PUQhSYQQZ_A2keKqCe1_3FTmk!TT&(@#JPsG{qf0rBN5$M_46u0yDX z{{!VBL`RqcE3-tTvl&1`pZL&1!KTQkDK_bZ>~2qZGAbU7pN!$8=;k%NVC>?HqffI? zTNx(A8GD}S9#|C(4zI_G$mw@Ieos>WXFN0wZf|_K=C*$phM<2c%10OLajoPdG*h6B zl}&jdcp(e5wdpZ?GxIv`i0Y~SNjZV5bIhZpz5@Gse!n_YFw;u7D}F=aCz+-rwTXvD zQ87DpMa_Xfs&2iCREj1ttofTQx=Kn=1FMZk&2t_P$sO9Ym- zMsu9=S5jKWBxiy<9FjBi$7?gFs`9s*B-wKG_}jmbRu{&;xrlU&A0bUcf8d;Kpn1(8 zO~detybk%^lM{zwnmmIqOSJW0BM*pU%Ff_zZ}3JZ2~(*#QGDXXw&6uMUg2?dbk6zu z)ZKSJkGKaHz{j2Z{w9wE^$UqEA{F;jNTHwNhp5)@?v?cGQ^FllN<7(b61sTp>E&NQ z2xGsmkxCbsAzF82adz1TY<>-Syy!H-628#-?DTH<7N?d!_wp8q3>Fo8A@$vaCkHeA|SyseLWlcxbcWNHL@$E3;<1M@XWRWiyDC%PmVDB2J+|Jrp(+89DP`BSHA{v(Uh{8u0LUs&|-e$T&g zsqMcSd8pYz7FE?Lmue$+=*ek1yjdX#6&Wp*iHuc)*ZC8 zY%9A#%0;{^C$?qF@{P@Osi~|>qumgfod}w}DMt6h0iIFhFf)K6U1Oo(Mi%z29AsBi@ItSOp(C@SXm;_l+P zLHua5Y*KV+&=ArT%4JZ94;gtB!Vl__V`cs0{dG(_5t2md!1bH4qHoyTY&0C85B~4y zk2c9W92A8r{cIJWFV@cJ6{Yo))DePW6NtZyGql(@2%W%zn}!`?Hsq7TTC7#DuFAWB zGq}x9(Vcq!QaYQ(hiJh+UODL>mwf-NDQ9W-X93dA(1za3^3Srhf}x9rij$$6sgtvz zjj)BOv9+nwzg<;~>V`9lD(cq;`igC)kY;yDKQgLNCK~~&)QbXS{#>KMw_gTL>vndD zC0QG$?h8sth&|Uy>S260!=x4wW3@a>q_JNsL(U{g`)^X#7j+`>FJaj4i)ZckI#tM(60At#L`!%iKr$Ra)p!!+(~5si3?%yxX51 z2Wx&9z$RoXKfpSUH-ZYM?WHJ@#$nJTFkJ|Eu(c?ODwRxM=ld+}AqQ()W&~ZM(imIx z432n?@48XCdfg{7fPhg$vL;~z#$mHLc$19{Ffa@G=%JyQdZ|$@#ChIU=rKG>b-5bP zEayuNWOxj4#Y070Kr=AiG+>PTJeFF?-%WJ_)Q@9R2eVD9Ye+~P> zt}etvKQ0hU6UE2KaI11dX2nMoVnAp+0{OyD>}H5Dg%Kb3Az1}V>Lj9R#LHpQF;kbh z=nYEGf2`>IBEN^8SE1Vd`re8x;)qpQzu4Z6)Y$!hOV%`WmnNwdH!!c2T+>lBP3gHzNm zxq;V29dZbwwP&>Pjn1j3QQTFd+YaFH973$Y@dG1<#YQjl?6lGXw@h2Xfbio}NY057hi=aDPuEHD5#%7XV2owY8!Qg?A^l7+Dtt#;J8b znnPu?it}Zij}hu(+BgB5!|l4TY)d}dMwb>m&0Ay>3zH+{nbf{_LN_PZ5@Dwz&mR~m zBhPE2@$;v^Ik)`2!@Hej(e8MXw(&fIh-e=-Z1vzObM78AeR}k+Zljn3+VWwQaJMOL z&_sQgU<|K#rSt^dlHw)%jUUYB07Nh*ho-rZhvn)_T-vJ88R?HlB)(LZR#8p)bho~Y zYgHd99l3@6QeQzChT+#X@6@>Ql1?h?Rik_@0Gb{}K}iP=^hY#0IrSH z`~_<$zT-Bq9P_Vu>~?kkxs_5<^er|a8C)aH%K zugqsJaEv=<%qjP1ixA6jtVt|7S>tG@+Th5Y!SKUiEPDxps@h*RpfE_+q#w3~-kFeE zE3%F6nT!&#Ek87S48ZUbbdo1t)~5|$mD5S$>1Y!>*wnzD#gTQVD}1vRFi;ZIJ< zmW}h_snQZ6b|iZF?&sZT`R-(KfVonB(IP~^+|88vNKe1`nfo+Z{Cxk)ShoFB_SVze zrTN=h4}w2P9fm%`db^)*@sSltkyXLX1dU9BN>m%#}Hh!%dWVoYYr} z>fREIK1J?FY35Ng2*SWBl&h31CKaK)Ia%u=g~m|bX};a*G-2ql#Yh{FkH$q92*0qk zV9waJ-vHIkPtzRkVc3CT3#r6oH6grmK+uz0Ht}_XEtoZCXQl_70j(N)0a!KcSuUsG z19ow=PcWNdSLGYAc;|^M=>@;W7Ix{2zwQJxP@=y<~IyE z6GIym6C@;!dI{M<#5g(#y5;IjqR8bsVGZw`z6D#0Bt8*KoaQaW&*O6E6%mm~(7c?$q2$cqFrN__WklD|_h2C8;-5 zDj-s@w;!A=S(Who6>BQE6HA<`o+Ryw2QWXrOlzLN?4Gt|`QZuLikHRBrQqo)I3#{E zt1e(Ii2g2LgZRb~-16Z86V`?3Pb&`39{BOXJg}7Zm>p;gYul6@S8ldM)w*}sycU5K za4nCmE}Mi+3J~mhE8Hd-I7}g=#4-aDhJ|}m!@nKNx2*>Daby zyOR!Ye*1jqj{EI<&K_f}QR5x&TK`nlQ&rD==A2bYBr$9z6+%tc-rTqgQ1^gBo6>eq zUuKxA^PvvKr=@$LlfFQ6g+(u7RBeE>7N7O{zH;?T)zCo;Fmm{i@}AzKMlY%sm{fLN z*xFZDxlMz+S_j}Z_Au%b_c9J`T)ag4kVcI<85#b~en7zzy1^ z5VZyGR;68Nz?q;VNncl6^nZy{mQZOQ4IdAMYZ(TMx>{Eb7sxGJDD;)2WltgrkD-wB zHM8mxbS~V}X~YeJNtkhdA$^aiENpS4{ock;L`#_TB&=#N25y3SJ!Y z@hObNytE?t@qB;$EP;y1Ktib@ZSF=}ylmqQVrcTN_K6dUw7L83)(jm(ShA#)EC06= zW`etrWSAjo$xOw7ZrgBp#tBmr`n`OrpfIRCD{ze)QSU;i937!~*m}>&z)&@LN_T2c zHw40t)*Uy^V+?B7soi<-7w78%`xi~Ku&YJU=dgy%zVc*1rZ+JoDWiEV&z>w09Ib?I zKP;p8JYNQJ%kpTlG->!C2IR$dJxecHyyvfb`5`+|FmoT zn-J2?6=2Kw|85k2%U_OXW#1w96$MObH6=a*LH)hgc4%c=y!Q{zB_x0DG#?LLVJWP+P1P+Wwv#e z(l%S*)MsbxlC`u>rGQW#rmI9$nCjs(qPc`RN@~o)cCu#^#vUg7%DI@>9?Q6=i8O1x zRs}SdpObM-SA&R?3;V2JHRp8nYjzsJefT$8RlFsXx`dSjVuvK@$&2niXO|vYEmk&I z(D?o5RPMa&-E{f-;dP59P&VLt8^^rJYiNh8Ivoz^H0_|-;Rx1?S(!sr?$7+!=VE64 z;Akb2gGv!FT2q)BC`2dyCuc4c!j48%?n{8FsBkq>*o-mD?x7hj)Nh4zr7u* zM;NEr$>SaUVIC)2`2*I!qZ-O6o84#`9Y%A8B&eo+VN>CryJM0O;sysCyl*c=DLW_G z+*HQ{)ryDrXEWNjg`xzEsiEh{u1xF*Y%Oy#N$#QQ-1$LFztn-p!ZkH#urMl_my2U% zlE_w9QXuYgC;H-w_M6ygD$lcS0B6L8sW?TmFpa#cQ2sfVpR8tq>b));fOnLOz zr?3cfrzQgAr02IzXT-a!#Uh*9pus`MMaF0gDkJojp+&i7)Sq+!AT2vkun(PwOx^4c z7s5`FjK6NY@Ftzb@lMhogH93jv%RRnY6(UJO%5tYP?6%NQ1EIxRinnCpWozn2pkYDhY{tmd!){O^D%$!QMd8{(+;R z1(eq)d~yCbe?kLLx8}4uSNWCBo*Owcue4NE{qNa5(!HzaaOY{FbjA@wxx86{ZChHH z+>7c>Fb+Gv2+M9Lg82wDUW;G;SuNH**GQ=^}OGtnIie<$n z^`}y@ROWpN25)~Ad-tXrCtF}^t`|GZwL1`5n&q;(iS~->V~ss~OIg>dL)V4dKPfcU zOHjEdjc#0kd(%tIPG!cYx!r-L8ua0u=1BvlrWMp5#0PR8Z{9A?tS~ag z6UKCnQf8Z|wpI!6$&s6AKW!Nd>4@~}UB6icLZ)XJapilNS~3)MpF5XN!>F%O_3-S3*Cn&jFWH~QZLoL~)d(=s?LZrMR_5g(>nIdgDZx)ZUE z-k<<=N&}%6T~Kdqr2Oe?s}^X67YL2<(+4yS$?L+JM~1V2z~?(- z_$3WEc^E3V__6twZ5qh+pnh`O_SkB2zC7O_N5A;+tTRMxpx1-#$S-2%3PZY{oW9P} zg~U18VUoGF@J$JOJ5{bg5Efs>JmETQynHwm9I|$P@GS;cP2l#AECrD4R8js4-tw%W zQkk*-WFXj~*=Sb6A#Zt}gj~5Ow91xf9@6HJ5%eia7;P$IesR$q8cPylf_(T;Dbq)| zXxg_%f|_9{R3J8+acFS)cTX|jH=#B4kU9At6thjmbDpyuJ@6BvQLve~6ShBd($k@Q z{endjJ5d55l1A}!*ZkR^&^F)M;<6Pwtz3)yaI{GNN(4rqV}Aa)|Mifg*5?PUqfwh;`fAn^Qam zHTHB%k6J?RfhgNNhW@+A1i4crR=8u7yEL4LALD^zn&<$nJH!76cHepG4)rzuAIlRz z4{4<%`5;)l^cjwctIvW`%qAG+e5TVEs%@xMU4=tE1^?xMe-fAAsd8uBF9Nm;?0?#V z1pe>D<$v6Q!~iZ|V#GehIM>wRORak`kHc3R%{`&dQQEd^M7kFQi}(sbY;7x#xbMgGdh-gtFBj zYHFd=)I>HnufXf!dU*V|Ql{yfqsQ~ZJ=vn(tm%+>78!{~J2@=*mSb%W&D8S)AA4CO zhEV!eMyl0A|KF?Vla~H7_pvHj>%Y^PIu(8ocXcivb1{1QM5$KOeVjQ!Hp}<85c`>s z=W}uMdjZxwQ@)u>Eo}&K40e7|D++0OL*owUb?H|u>8jI?t>9HP+y%9WP)>=2}lD~zroG*xt( zwdR-sPm2+or+TI{oM~24D09d^@ycsx>BZ?@S=S#!br&(4}NqCc`Ozq~K>h7r@J-x#F+>F*tQ-M3^t1rrR;QC;+Q|KiTl zld$dGt>E%7`%wg|2!ao8#TchUOOx9)P zzhbD)=|lW_!{&OI!zdOnP8f&&RYnzr*!D@8Xb`_i%8ai)vg62X-Y1B<5R7gh{|POI zE-UV%FJ8ywf8=#A{@JHyoBDv3*U7Oqt1J@L3dtSnsFPzJxKx{dfQ5i6(V5 zN7Znir)<@5UB&5u&+jV(z@E#=N#*k~K~k?8U|jd*c+K{WIgaI8!aM+F03gZikfNMS zOYnyZ(M)ml-WTck!#z!|2FD)*oY_2(fn^EJjWe>T`SI!+A;x%5WHnng!-~Bn6Ib`c z4O%3BLjh9bC#YSr5Py?0mi8GIx`ECZi+O(+n_JudxWkdj?IbIuD3Rf|e1CyX%zdXRDT;#LU->$L>+(j7d^=5Zfp>{&T190pNJCWSljaBbJ} zb82@O*Ur)n<#It048u?sA`AlBVE|%sasEr<2|aIU-KE1f0p-ceoq7av-*hcPo8Iq> z-Kd3xwR*f*5T(pO$uwoiF)(8H_ieO=rpO3S-)~@mUr8w`-5Ynh!8d)@W~zzt5fdNeSLt> z-Fy5ujQX*g!7d-%rs*nr`)jCf(`qgE<;=#5d_hNkg0?`zQ%HPae`>y7QQ#OaRn`HAA;>z{&>6&k+9?xyr#b;e_>^pjzx{& zBxoZ_=xaK1jmjbCDtLe%e9D_izD!6B-t;T?T|Ydg^ilN*d}du9 z(K_sr!UIgf;7=vts)XP5oc%bx({^od(cx1#uvG@wWz5`~>DjA0Y z#&ferTaLE-Jj-*x!taWZ)?R$>5g-2;`$7L|(4^FSo>X^lUhBEJoRHp;UHG0}Q7O?&4PLEINIa^tR;a652@`7wH3U}; z_ndH}X;8@Ti6<3Hp&M#5;(g>Yn)C@1nZtmdw(D-FM;r{c50L6-cLh&Ewzf{oeGL~UxQCrN5GmSmlqglj%&52)kY>j*{B~-FWBP{w*HGb(8g`<7G9S`ZMj%spv3$krv^84{bFgu~j z70;21E*#kzaUQAHFF~T~O5+80tva71^$Gnb&x${;n6Ow-GG7!hW3bRl%65T`;}SNr zKDtw3=1}op7C5!0_$Gp1Y+>-Py!(GgYT5qhRr$ZelX?a9##&!G@`ZkBVQl!?BQkhHStesG(d!}{#0To)^NWa5C}UeUDm zFEQyD#mwiT1y*o5U8x7-E9WVXrPrLlf6vD?za2A=-*}sor+HN{I^JhE!n~y0V?2h~ zx2JrGqqm)N%m(S9fU?H0SI{b{ZE0-deZEJFG`RvA2hEfy-c89>H`a63&s_ALw|taU z6SixZHqG)u;>7%SGC^|IWN!9i0qEaNm5w(v*#_muG2o~*Q|HJ>VVk8Gr46cKGJan% za5s;`in`4C)$?iJkN4fuC%x9F&GgniQ5zlrB%e4YyA&V)RrWH^PZQyXY#}QA&pzF6^AXg^%ot!#u(EblKava>xB>& z{1uDm*!hXz5L@BHApw+YCH9?b0a$gIOmJW!wUA9G4HW<;8C(p3^~)kQXdjMWxWD+k zqtu4=VvDW0O;u+471#+37KW>saSAdv?D(TI*#H}4@RSS#s_fnMgIpny7+~wxwD=mv z4<2dC<(NnWQ~L9J6M?6QM1o1g^A(R)|0xkFs3le*{V!$5I4j{MCETq2EnQCpv%MzpH0uTOJ`BE{V3!zQOrXwnpEr99$3!Yks^42eno_nF7XDc z>{`=nNId^&6F$S?dY<}6(w8NpgYdj65)H`)L3vqxOF>f9KF*j!%WhM)Erj+3h|G_` znvcj+cD+f}h;!(^O>a!Y!ApFR>*HJy(~dQG93dh>#nO+HCsE!lR> zwmHLg?!taf8g$p<&()RL@ggs)*Dp3Dq7mItmEt=zc5vkN%nAE;sUVr4h$!_)Ey4&G z8j=WgVbF7rtDMywKQ^Kxr_ayq&(Gd@*K|=md?QbpP(=Y^rZr0mJl3DRuk<7fT z3wU-4aGWiilntkPEavFIRXIr>UNh9|73%e|bv?YMJN!sxUglKB()-C-W7?FK^(+@s zd;sloqAQ@PrFwUr{>qI*a|#htm6{}ORUua`a%H2f-lc!&Xjm?SXeN)I2iixH#T-_{ zJSVXRc^F4#ReuJx0ATJXDhvas&Ve1n3}^yHK148LZTIK=gwadt^w%MKpK}bJq-LC zl%u@o!6??*H@xO^XsN%G{&6Ei;SY2?=COy%fEw@+dq89g!0hnBU2NFKn>URcM2o2~O+ zPQC4hny9Rd6nf!}AGn}eu~}fTti0|zf0gfSjbe?Q#@pY8>G~(Xvzb;CvH9rs@&Fs) zJ4KAvGJ;$hwo8p-8?Q*CFq@3@zqJ&mY)tB~%uF?o23=}}(#hBRF0F2{>@+)O z*rx2nZs$hxqxA^m!4wj}d!O3`K^a#}8I12>)1x`(#B88aLf$u0}@;!!l zlKu)J%zrt1U%RxVQ=jTQ4!TCpW=kV&r{57|B(T@^pxW4HM!KCQM}WDtwuQtE91X0} z7<3rCNljajRyb3^O@;pw>}&Tm!F0E{4<#}<-X*wq^l6O4#OxC8BygBX86KzAFlLM3 z^y=8Y_+WuQ5Qw4zxIKj*&qGM&_e5KZntr7|MnoSM`^YHk^skQ?~~ zqf<-2)l;6tU!&bPvGNMyiI`gq6FxR|v=pSB`jBtdEE|1^Q4QW}9TQkK#=Y%aZe2^l zsWvBjsD(s05DxMz?wg)L&CikSdME6Q=0S628r1aO+%H4ubRjZ3s`NVt6x0X$&}9`a zRIZLZLPE}$FM=cv94on-zO zW~f=K#y|G3B6E7Rvb$!`tmgS=(>B!3yk}UGkww#snb)$*cVC!pZeAo4h$-g0ItYtq zOIGY7h!$EcZpp9=b{W>V$Zs-SiuP3n1wT(*<7;$h^zKio6qBA~Xs%nd5>PZ~l+A`M zY+%+n_8>;V;ZXz`SU9Pg`^B@KFVFZ`qRRuf$*GSL{r>ce^BPjWQi8X9h$)xy>GvIe z6NqP2;z6OA&%ILdrSED#jehpqd?5ch)isGja}BkJ*i|C&$0J6taSWtwm#A*I z9q~8xV4;4Fen(w-=wmyE`NG>z2*Y{Q0NE_DutuC?=Gc&KR98CJVRq{GV3n7l>?ByU z>c5nq%8DOJ{@x(ZKko>2h{~{@Ip&9dp}#cxlB&sRmvmmwM6rpdlvYgs3{h_C8UKXe zR(<{81@#+vMAUc`nV5>Pf`3M2-#Na`3lc|k!+jRO4;wC54;UBS)ZzNT{Y33S*UMQ< zPc+u$eIsOcB9DqIrAK6MVZ5u;4Z83o|3R%i06OZ+sO^|-Qe%V&K3K+WEA!@mk_Yi) zsP=$ zq)HV4M>1UPOUB(VUq(&*oseN%i}SB5^cc)z3%oNwG=<7)Cw_9unyg`>x{OT`x9_00U;TQ;~3+aXt&l6APj)LnBz zh7h~KeI49pMW!x*8vxaD*Zu$}a#M1KJ9g}8!p8e+eyk33yf)Un(R6U53HGfj7?jfG zk7CP-zSm{r`BANXi%NxmJ5nsChuE}>ZawSmIVF0P`6-1Rm-!vHtMjIs==r^$qFGNY zG};IhrCFdyzVQDPN)wAVh%FAtS^Jx)cb$`Fn)+?jrjjzwP1ZUJA2#rI$(!;K7oAXJII?0lbb=RjUx$~^bceAgZF&ZWOQabj5cUraJ zaioSvS0k7#lHE&ube6HckoUuO8@jR=F7nGy?A0+Z6i69jE_`Q%!}R38a)xQaXEPlq zy_n{Gzisk#NID{~@7o z*=}!VpK@4PUYlK8;)&}zuDiyAm@@w4=HrSCzHN5ue8EG=3tmj7GCp9bfql&aX6uW* zlMQ)#;$=Xi<&rN)ALP6dh)tr||4=rq^Tb&>`LN-rgMKD%hqEO$iQ@U0)6$y-x-IDl zqgx^O-cN2cwn%-T|3=qqa;D`77ky(eW%H=Le~NfbYUbE!i9)$oeJdI+yloPP;ebq?rTXX7xkapu^ zX`FHcdG$1&*AGi5r1&b{snnM@cx^p^DG-&(y22G%J4AVF;=8yT=k(?VZRqgwit-z~ zhI%(o_IZix<4}aoR?N@x=J4+Mf{h3jichQ{w1V=gHhhZ}~vsXYfjr^B9?-wfaW`lq3MK2iVr zMP7f%KTqI)&SAb9^gsFkG#)qnUw_+8GfRX$mrA$0cMjcD-hDJ_b8b(h*_R zlPic31J#5}hGXf6(%Wb7B=!Q2Dt7ohN3&FazH_hf_3$1fYHXCIcfo{v6Y`z+By>yx z|79FC%aTWg2!6Dwc%ZW2Db*MCM@t8;2uBvjJZ^`l58xDtD zL`j}T#wN|7UcAC0iI!P>3?}^_1Xz3?B>NGs|OLNp5Cb!l2M0`bL1v@#0p9NlA z-{AdLq!#zXC-zEs(kmuu19+?~dq5;M1NqRdX}5>O<_lWn{eroVCl;1@82X>+82#DE zY6bLA&Z)(C*=*fU)$0?;(wV2mZparx&D30iv4KU(hBmmtP}^|QV;yX4i9+r0NwH((>I z#b@4ue}8F7d?EEU#lwePmcwO>LjP{;6a1e70+Nyb(cYIaQVZUHf~x5M=ge91U$)um zU*@(_4tC~p4h}YMj{lZL$ExTnE(oFV_k&#e=eHK-KZ~ntp|rCj1L09nlfem6joh_S z^EgC#*XemL+2%1sW5_j3ua_}I?wjG%K7`}{a*81rIwkehxeL& zXFWn2FIu8ywXXfPPQ4!bP~ZU|pM+N}H@_7_%l=gC zXkbGyEW*p%wk{vCrCwk~%|2lQx(_!m`IgQLl>FTo;7PWz&_mY0q2c1wxXyEO`HQnf zXVRc$-uB7;>FX+z#U%$Z%0=M=L1QLPJ!~=Im*fH^UH?(0SC837x`f;r2pYH~TrWHD zG$jUOm^ADtZ0SlwsjNuafbz3!vI;18J#(s862AiU$)sE+x+Ml0?cZ2GcW`Rbn1Z#f z`E(=>m{&eS-zzex?01f&PWa@{7N#|A_BgyMco@yoE8ZLb>Tlo@W704w)0u!gVGrfa zXU$zv8qElr3@Eg1uqcaUT!kOd8^_QYeZZC)_zk!=y+FHIwyJlD4r5m#dfpI>7=!Z+ zD?R_qo=8LngK7Ay7?JTGixL0EB>L}S#D7hd|HCBur`|*+Z2CV~shgrsE zt|d*^c`B{Bg6l$cdCexFp*`?z%FWqvu9|aJ1Zmwg@jZVNNag}KA@sj(Pkgcpb{lSg zV+t+!F}-=k9FQivfNKrIoz|XgTA_a#JGj(JQK>IH0jk|6)v0GZ@euVu;qI1vk78F` z|Ddi>G(91(pIMhpvK{ueZRozlvZ4}^Jw}u_LBYxTm-!p9(epuj{^^t!3X^kzih55U z&>Q}QAKa}wjS=$kM`>H@;=2zu9xRvPK1Rx5sY>)=rfXJT#gF7IDGz!`iZsn>I0d56 z-(b2Bj!TLOj)Fl4|1#<|#wBn+{&J{C{f`m~n*S7e|DW#sx3HVk_VHCc{QD^&otcyi zK}C%Y0#cynBVQR2A-o_0t2Wn1r36ZqO;Kh?Hd-+Xt#o~o&C}AB<&tB6-%y>ERsjbz zDJyrG$YVM7pK6PCdCFSf7}R%FZ9nFx1SE0LKfj(2m;E~KyuRnVcIoasZrhLN|87)K zl3e$hX~RL^-B2hCeWhVq0Ana#*HQSJq+I;94_O@1hS@<4wxW|jlk_K0$*WOQ+B3Mz z+R=jqTVCzCJw-~Sy7uJ!Rw6~fVI|)w?58WEIu^%ozUb|o7%@-dcpOD0bpx#}NB4eh zOHIAYZ^#D-^w@|$ZTgT?lqv>&aD4V;s0ul*Vrl*StUH~mZ`T07o2Ylw!Eg&6Sj^++ zu#`>sV{zLVRD;{WczZDp{radE*WXQF@xA%*&b5^rQ<%OO(QabWWMm^D4Fu}jSj(;y zeQ)eG6tPifI7t#B@D%&TUENN66EKw7=@dm^^U$!RVJSU0c|(xZ7CGrCs0ulb11k)u z9tCnkauXyI8E`Uv)FCJo=gUE1lUmH$h0N*>8x5n=AxAy*rW{8o*=@Wi3gl>~YpL?p zs53g)cHc3^(h(H}bSgt&M40nddux!)nJvtfU79Y%$Q6?6vC10N+gDo=)Q+_$Lz0wa z>nhVIS5u%47e8(-^pzVYBfUM%7YYLH%$-q|aKI;rVxzXkCHR7k%)?d!e%^))(AKAy`iT6j87kUMKZAzx zd#Wek-_+Si+MRSsM0s)@ZYrl7nVlc}JE3|gR2EY$;^zJx6&ATOl+Q5;h4r{mpxL;C zs6N=J!rF0X&Izr-Jrmf+AS_JGQ)HV^b8hb&=ycrq6l@F~vf4Y`ZeimX;^H|U0&Zbv7K#OlgNdq{E zwy6^0ucE-)!E$Lx6Guy|--q_sHxSxNn*A328`4Ky>zY(82M<{^n-(ldGjnwTP13Ug zRdZjj-UYrlX+N`9D*fJ^?dO1qzdM426x48=g3{Oh8G<#(Od2G}cGsyZSLw~1&Al@; zl%#tD_x>AN6HJ6VEd-GEN3KS|M~aN77R_j9omZlB*>l#UYi@AZ_yA}BiFqwd!oF~D zPQnb}D?D~|Kyr2dfDcd^!`~%I}g* zQ!^9)84j0oHg9IJTr+(ou!HMM?+Enfnma+HY%TYXt1A>;L?sw>nO)+DhrS+d73(h3 z2}y5PjQk_M;2qz>y~fzAA@TY|l~}CPPwd2*hoXYo>&aC_s!6QbiunX>(49b!3;`*B z+d4OW`YuZ%gc?NH2k^p~il0$#&e%!2MaK?q4JZ_V$AmhxQtu0{>S2aCPZnd0rrWLD zU`qcob2#JFHn+Sz7Hy{X^W7lzRO1>8gbwl4?Gwi6QIZk~v1VwgY?2b2q*z9qV?i*E z*r{QFGnMEuWg!@1&OmY0X&U3!0HGxJ`xH`j4W4h(W7CLS(0P2x4 zdF*YzfR<-IK)}bIKpcAe=wg`OuA^O%GYSRr&Ev)d+Mvgy4G@Vv{&!M-Xgk{zdK=Y| zv9Vhs<%1zbG3p$bg}|UrjrCUZ1{8bvMw9`=pcYi{$izuRII}%tQ%(VRgNpo(vhqG} z%oASF6uWEdGOebwcq-8FMpkXM%|VvymbO+#i^p0b?ea{B-E!WYKrpC|}i9=wX!eMSn_e@ml|g(%ZiVkdsC!PB}*h$>?*^ ztha?b)8->neU7Iy>Xef#$#RF;w4~NmlGp4e4U5u^0EF|X4PPLJ%`yx6n)H20_Haaa zx=OHu1~ol11|YEfYS^kks(fPKi?V11I*?5xry>ZIhMpqZ-Ectd_3d=c%={-4)2;ZGo zWCD*#4J7|%fOL1P*c=9j(iHtM)~dtgO-^Zd;Gf2Uq{ugaw~}1mpS^{GM_BZJ{461g z=0Ry!P(64NnWM+jXnb7!Bcd%FkToJ6nQE2CWeX{Zy*Nvror1DU%k|sc8SA#M2AW$y zGLzvuvRTP-GQeKIJ2@gzZzv35FV`h^^k=wiIb~+di7|p%{OS=KSGi=VJ#z=$git6O z`z~^@PHltaBUQaWYBI4GTSca8`bJ-v_OSb{&Ds^24NV_)MVq<&JjUlyjtwU}`>U?I z{i)UJFPF`*W(>-~*4Sbyz)^{m#{E7V&!Ch@nyOxU#G)ZjZhJ8BLPSm@_R?w205!o9 z(?>7X+DEHbGkq!nU*6f5tNR#teHXO0)CMfa=H5Awsm1<5;+J9Rd1z5Ptkp>E<3q%X zS9dwzx}4$X4>`^``H&|!4m)cHJHvCpWu#L8<{elPbWWL}Y9+z$_17m?>gXuqcu&it zm6F=1zaH9AAU@cB*FT-y=1j&4ncyI{5~h7I9p_XuJAgzdK1m>mJt%a2plM1#!SW)P z5EZ&RQb3`cib(vZJ%6wjAIU8gGF3bD7x`?NS-Ys&{m&pTt4?S6P`D9S-rI6h&O=hP z&btw&dY&TC!HHK_Ouy#zSudze&2JSM!-El}A!O|xb+DL)G_zfJ7kuN_i+dfM;YB|w z8aSMCUP1io)31scvAG>oTxzY@4__MOo@O*<>JyoG3&lD_WXwO_70EHf)?rX^%5Kp^ z?IS4!yJs|PG|*{bur1i!9NgxD9};3nUe4fn`6oV@+#R`^CD*GtUf`A2)bvj^f+qC3 z#p0dWB!@AehMkMJgNL!YbVleXBV|~1(aIH*h@+@qKAQmq-0b#~1DlI7WOK+E?>K(3 z2xG245b9-ALUun5DSYCef^n@zz-NqeXIWlz>k0ZuueA8p%gBEY{R~VbZH2nwvN;w` zE<^2W18;adPz~@03CPYxlAlHH+Yk{MM&Y3~C@j0X2A9Y}RR9!D#=2w6k8)Bp6Qc5E zir!|i@QX@9rzxN}Q`YrHrjO!1R()xsTf&@~YMh1bIj+Q}a>mT>RM(!zZM}2jpn=;M zr@R}7`PYthp%)zYFz-UyFZ~yX4o69$PECiFq0r}VT6#}jEO|_C3f}U* zM_O`%hY*$<=2{s0$9mclSrgg#PP@Q!d2Zc_amG_kmiHk4OR)jpm+Ay_pAXGc={ot! zcY{*R)5lH@ ze!Aaqndot3VJA55Lhr4TCCIYWxJT30$|0DqUC%jTld}Oi6OKfsG4}9GN|&9u$ z5=0yP>ISXrM=_#9hj$B&#AM4Aq6g;5x~z@cbTn*6rADOmC60@|9}L*n>CKx?+sXl| z3aIEX(d#KS#j_TX56e4sBO8s8*Pgci2w6M!1fU$zaq+rz%;L?IMf%o!jVe4C=3&Lq z1eei7!f%a*SO_1A7?j;zebX8rxNhhrOr)WAXh$V=R6B|VW9msF``@h3!yNw@-?$zT zhE%#>$p<#Kqh-!(Xf=_XX=ZlQT~kTM;W^5gs-?xg(~ z={HvhWZ11zk0tI<|MzQQU;5B~fG>Y6X}>4U4((mL9e~dTYZ}?tz2%*W%LQTP{)*)G z&95&>ZjG|!rs#Y7Hhr4`dkl*URxNXl(EHz=5oUu=bC_=IA6c_x9Ea!jk?NlkFkkKw z@Ns-2ub*sxa0mQP$Iw2yQ5#-Yg*_RtB(iAp~IG&fSyTs zBsx-f+)lC3uyp8#1&$)-%QIr}|#7Zn3PfioGXY zOfhL($c3ggbd=VGWeYTO$xasHI2*X30qu}DDpwxRJMgdest97xf4yamZ4EM zndCSj)UG(K77KwgPe$H7cUA^)w1M~JiBZYej=Sn z#hr+Knqc2wLE4H5%=n1Odq*JvI?DCI_V8*^6xi?1{X|ZVToCB1m{LYc?FI8B|HSWI z0}%=s1&MX6q05bdh18w}?Ih7obg(Ll_ z!wPMqEA+1j`7bXp+)x2CWd;hO84Dw1(A1l`j&f#BhGJv}N$#jpT<}VXQEtg(jQ!Pe zHb|vu_Ap+dkFN9<9HV{|hT2M_VVU4k?Ji|CHRbywg_7XQ$%hWLSl6bnET@T(lOl$Qy({elPebpw{qBr`HZf!rvd83w< zA1c8*wU(Lg4;Wp1jCCAk054?O>eTRQbF{Mgyt3VTIL>-gd6RxT&$``2E!~h+BMvaw z>sKS5WccZ+(4~U=q9w?=c&f~NOJ@_nJC2`2oUsa17{jWPz6g_h2oAB>7lZhC`)bRGhIldz~r2=o^{1pp7YK9-$EaWX;u4W6b=7_IuPN;UL?$(XT4Ghq=xG|)Rn5&xu zeSqS>G5iN-?&-;Ui$(eN?U~{~;mjoeGukEn-<-&QL%G;v7EGmfFbLGK{HF%8!!5@4tJmAs)wjB!$RBy=j zf!>Px)GigY*s^vy>r4bV^W@dk)Q*yJC)6Rj50P8It=Hd=EVT*zgL6yL(HwveL5z?^ z7|~_(TE9hBNJp~cew%Nrd^wD&UKu}-nBF(m8lKvI>4RlNF}H z=3u1X8}SL0ncbUSXxxhtkzzQ>V@WM0>f7 z$IpTDj&Ec#C3_iiCY&az7`!6eBHJ*OSo9r{o)Zc16{KuK5)+ zy^6)_cdG8~J}%LwX~_*$K7_7ld&B39Q0Y6r*gP`izZTOl5)=kk+hr0xB{26BldyDN}JviUAHlzl=(ukp@k37|4eXe zqJ>{tUr_GUe}r?1{+9{)AqY4+9k%{zV2D8zZaw2 zCJ-j=ue0^JJNUOYQ6n=er1&%z@vrNca_b6HGk!6xnp0G+byWSS9(DC_b}yfgp{O2P z<=6e$KAHP7qR=VR+&vdyVrSxHA7IIYGuXpHn+T>3M^|H@Pm^qkx#lSR zfn%F#acLD_nv`gF#^H8(sll>pH6%Bt|2|wMNL*2L=c=CRdP1YYdprY@XksM?jmE}ocqW>$%RFkwVt6DxFxeo{m*K-BN z!`+Rv00iz-5`D9FNeN?<94J}k19QZ9d^E*?6=KEo^kJ<61d7bn^ma;X@dGvo>E!VJ z%`-72_4Kl1Fk4$3d2OriZRv~yr{iTM^R`ecYk{muXCIhdi^bsG5yV*4<90V-wA6!D9jNoRK7*h{5L%;EcK&21y&X)4BK(bZy0lw+V^xjak& zt3!#J53>N*cE|c3fWC6>oGCLJYzqA}sq{0s9P6%MQfQiJ(lrreJ=%P;=S7VdUuK%Z zji3TMjCNR;^0Ehemh&pBh_bkXK&PB3(>c=76lY#S`XVoJHOcXe(m0Hn23N8*;xWTW zQw>@_Fy1>foNR}gGiAI3*K)bqE!oNw-xD!cEYL>v&{P7>WPVI%n|ul4*#R{{!4>2d zV6PS*x^4WhiUk=4n`zh1aH`yZj0U9U)rs)%8C2h~@!a(gVdMo&In=N2qbhE5iXS8{ipv$_vdHxd4T)*-8Ji&F)ZdFi80ys(qF8bg%XGMhzowF!kZ>e>qD}7x%R9L zpU^PsOKTn@5Vi@GDKY_Y(@r0x(|IL+fY!{#jt}eziZ6Se;=HhdC0v~{sU{S~RlImR z0jFo+Npf&q%u>uaUCH;>Cpo^qP6sOZu;u>peejBOUY@}eDiejqr2HP1_V*$6huT20}kkr1qHK)N-VpvbzM^&Asmm1JGES`noIx@?~_h(eYOp zLYbo5#*=;pD}KfLB_6$=mc)qA?wKQtwpU%Dls>*F^8>AcQ?(UNAZjkQomPR(6(hY)iNq0&~H%N%mA>C|J z!hd`2y`OPCNAEuw3k)3i1*oO}g1c#96bNY8@li3|SQFcTWPfIPqxThf#_1oht6o1)`tz!9Z3W z*B8!GNutS9lM=Cih>=@wy^*62k{MBvg_Bf~iN9=wje^H%Mk$)cRdUU!zN&*?o#=m5 zB0}2pz;uW$*M{A4d~)#Fl>u|NF%CmV+jaM9%0C$ROqxG^T0j7<>m`(C4z%bIroc`~^}J2u;VjA8YZ4!&@-L+RA^~2R9mn}%t{);l z0bz|u3EwbG^|;EuHR5;O3n8BpI(XeeGi6GhAVk+y5V0V1Ic0io=ubaffJ8c z8CCeEBAAWO=^pZ4{QVc#UJ)-j*Uyg4yn8kMp4~dQ4Xq-WgC{OSLsMgr_c(}h_q#k!MhChDj0 z1BO>fHx$z|;p2m`rc1s&m4uF8D(chhQah$K{LyDi{4)c{z^&ePhNX|R z!u3p?)+4xtk$Re$+)n{G#AEGJtJ{ZIanUIMQ2~(D(&=@Pp2w zhR98d>wBgVNj#HLBb%%{7zXEkungTwQ(v-RawhU=y(1iek$*(TLl2s5%NjhWPLm#g)VdDK%2MV{rfgc4`X&B8Y>CXu5pNZ2(K zBL+mNWn^`llU|SZAgnyRX5_m&Mrf4C-=1pu+LPF9h1A(^v3BeHYJ^~dp z!6&a;w2+hYN5!8^ipF2RaC>%|A|AZ^X)1o65x?TVx$?vrSCfpUVBKwOWPd-S?v?sN z_iGXTcg-fbZ;N|UbUDjQb?i=X8v&^oMUX2wR|rx`gY#>dDatq7MD1|g98dQy z-01N%92~3-T6}@&Zqf8e28`oXy>kimXtwK*f;Oa*x%4Ksy{|D05UdTVeV1)nyMMsKjw9ZKn$;Q=iVkai~|Z zC@$&EV~3y0J6Z!TBHmt*aVK_n?c;k-5-Fa{-b6~Yl72+H`e16mIJscj-XwE7hBX?I0z=P1>gP=|VguvtOn9ua#y8;(SyqlAHo)d>;g zEx$IM3;wWnU4Nz_Y93K=1$ltNi`SjdQRAUc81`PI3nzUH$zK>$K5;t&o)O+fui2Ok z4#m);wB0ej2we%qL*Kiw6F7o zBgyz;=t`Jr=(YL9U|s(W_lqlFyTJpKrJmWB;I0Pa^qt++G*%egr`t9Ul3sZ^h(i5*q@!vuCVk9J& z6`;S5D|vujgAFDg0cNzd^U8tGl0&>pi_J#e@O$MKmMvsrg|&xx5BvHC)aduVG^%UjZGc_NfNnQ*$pY5QRv z;ZuJP&r;{L!qDPFCOtKfjxDY9j-<;GVh(;-i}!0M9mEihS&Cy%Em-nOsQ?7rot_o`GOd3uQ9#yhB}jCRZCk z4Mn@r&Q*uP3okFB}}&Q=-pBnVtcfi2?XbnufKM7zKRY zNOz_ztk~m)ZE0}N5976@0NzuRfz9SesZdFeZZ1jKY$d(S`{p-g`isZjZw)@Q2uC+c zGa$5uy4xJV=^S<|P|^?HYZT=A(xj{pMfI6JJ}Ej=t$tqz?N^T&}@~oR~ZPXGsl2j>Mhs(yw zQ!qGWKyo{tnPQc5u`em-vFvqpDVtHv2u45TuhO7C9#Ztu=BVG4xBODIydpW3NX>0e zDQ#1x>=GR{@k;KrkDbwrEPE`Vd8tlc>@!y;AU;a79bfJVm-Q8 z`@v1-n>f=2@PmDd;MRu~c8@^2RYF>#2PnDCU72)grm4rmnb#I^Fe_BU#~({C-f_>y z6vJ5w1mEw}xU)V_{?t#DXXM4*R+3FcTtK_laL>_jX8^CZC^t=iT=-J`YKrz&&GS+k zveDxV{MC*mUm?F3(2?pGY_|L`-{l=2dE4b<=PRTR9p5;t5d2%~(_9yV2E|U7EuwVo zBM&CnFg;wI+Q_zKZ~#x!g$?x;lAvKr;~iLq(Y!=4QGxoJLgM@L>G=r63fs(c!JAR# zk@=t*ysb0eRx9TB28b^X1$|E`p|JRnmBS=arU($n;ll7oKuN+h7E4E@EIlT39UY2_ zcv?Hg{gKng<8)=O!5hpoHD0Xq_(Wo!hn(wEn4u=;6vu>7tBh0Y1V_};cPC9zR;X;# zuIY(~7&4Z*dj$Ea!1t1O*708cg<(~I>3O^0(G%+Twx zs3mIr_-0xWl8(9pJc8yU2Q#0XRo}70#0DRigPy5s3%F<25ELEv!Awkmm{~~5Md2gL ziA9_o5L1+@ur*;_atvPdO>N8w1h?$U%-!#4s9bw_6cY6m`v;B}@5&xAf3EWovO+xm6o-?f5f%S^?ZUJ_P}4~Eoj?scKKW4vV?Rcy|)3dJ&)TPY>xlv+F@y`GyQDb{`E9;bNONG?nul`o%goNp9Ie4DPv05{6Ij z`F0fXur3|IQKdmGE6D=OUYf*cW}fi{bf1$zhB*1j@{lu3HQahK(QH=8o+VTr^7aox?UIZWa=fse^;VIKEQ| zi_o|R#{^0XJs6l?^4hfMIGO<%14I|($;Bul^Y}?ZP#XuqWM)HkNXGs6*ge32HJlMW z4ZfKRqS&9`nX@A3aXG{pO)PB76}yu>^V$>mFo61P3u(dCyH8;Kc6QHUO^*?FF~L2A zv7IqR?S&k1$Y?I9F^uO$RaPb{*5cyHwJ9hvKEI|g`b1NS9-*)a-cA?0EJ40&-q{)| zeOxRoJdox8rgmNMh-&x*=JDkvJXxtOUWOd^3)CXcVwYQF0wSH9*c#yg8@Q{KD_|IM z4+~m7M97tU>#IujLnPNS8~c2p7ZK3bC0$u^mI~V@nM(0Wbf&Dr$4}EogQ}w*A=Ely zlbiOwN@v*-c5n3@wKo5}9lw2TJ&JoUf|eGiL=ska3IEcdFoC8P+`t~Tl$*x{EVKgX zz6pj6K}g^P7VH7Px`5~@PrG^yh|-H7ggfZKzp{b%ExJqSs zq3rzX89-x;*Tvr4;#&3Nth&~{we}bnq5`RrKbs0)2U@XxV}MU`%(A#wU^UMq-81y? z7n&1o5(G1w+ylpID^V}*o>#b7@F>EzI27igEz=T3lsj&L`LTXVL0Kv^@fdW1TpSC( z9HVTbHzIK$?*sEK;{b_obvJ#m_+V4FY{MSzd44Lvgv^uK&}x|N#V4Tmlt@FHuv;qB z5#Kol@mOQ-VK2@_`Y5iQcT4WtJ$@X_k6nq0o%j>m5YM$@G69z6Adw#Zr-MWcC>TJo z8*xlB0`x2P`&PZdI24ouoU_(Vn+#Ej82^AWuXKHI=E^2!<>37_e*q5T2-|6}E2XV~ zL9)47UX%SPe;`XR;E7Mf10t(mXh+U`hEX46BP1N}-D}I!pStYOmWv4Ob+l=R_`FJ81Pm)!7f?d^n@6=ZTPq{zEvlYGHf6aJ?eber}ljMKIEK0ed zN`M8$51vhD9+C5I`w@{i;XT-wn4yO=DH)IPBu8f1j-W{I;kp!@lddU4yff_u)OY~t zu2+3q9{kpeG`6lPHH&Mpz&Z6h*XuQgHpzGpG5?rW5V`>yg4j8i>_>!qd1XE+BgMs zB0CKkoL`}JyCYu2!=#F&p%PM z0xQ?CPt6`98t82SXp;*Xk~4<@p$K zSCS`3DRYHg9}mh270lD`$j%x_aFx1KFBQz|S~b~pig=W`GaqUm2GKwk_#_dj9&Vhw z%nC~RsT@Y0m)aQSdlab0kyX4EnH}F`S6>*$KCNrZ=XNFZBuZ>z^Q}6Btq|c_6;V^o6?Dyhhr!)wG@C(*qRRXqU}7Om)A{uW#Qc3JbHzD|tx{=6{gj`qx5hmdylFC&?$sDN3e9u@Bs|+{@QsEKIS>CUV@5Se%5uUbK&WsD=Uz(;x@< zbX69Eul0+H0_*Kw^ztcbGO9=t9>JcM^Lr8!sDS<2BrC zGd_BZ1GCt9*jN1g?xBs4C_|gV!jwj;W_jnXf~S?a)Y?lbOIvNdi~7W--QXJ+Pz!Fm z(fCp8Kdg(0IKufbhaU(pSvk|AmX%s!*d1YxHcH8yY~dAabpl4Y$VbT5gs;I{5|o)L zu^p?*93|i4tUuv8b35&-hwN$F$4_4ahEmq23SRNA*{aX61Xme_8=IsOJB_W!T8I3e0 z>VOtvkMwlJCLSXD$GsPhjOPjiuceRFkQy{aXzZZadz&9`zT71#Dig@Pj-z>dDEkPT z1-pk~3%BSwB+VcTO%?_Nb%2EYK#jkg8k?hISgvbp${5y_t%(p?3=>_8P1TqtPCYP= zU4ls@*{h0eac{)I{zAbM2zV_uZ2s~L`ibD1k8@r}$2usWR7oqh(qYON#G)w53(Bdk zi+ZO#w~ISt2D<#Vgm67OZkJSNK}7L-@S3Ud;E0NrLP^Z)=*m)Z3R7yyx6dRxB_PUM^uJ`+YjbTtc?kcU6YF!R zYGuxNyP9$Q0PPpV-0uTzh1ON5ZOg`fyU+w2Yq~o2`*KF_4+rQuIeEA*EO9i2GSI_* zZ)3-+!O)jblc(>7m?+oNsG{zz9=C*9w3n zz>n{V@2*qW!qIxQC)XoC;j)b;R)9N~!|sZ=Y@mC1`tHqR@ySB+s6@p3=nuFH93^ao zqtlaPsA%d^4yux&)2BTWWIG~NG1EJyJGR2nf=^!M)}|tj#2v$!AB#I-1@S^V#Te(b z^h9l5vr+56EyFW-I*Uxm0_&qbfI80Zn#O5p&b{Dd6M+IS6q8TJwcvirVXq{95=zG( z{CIe2$1TPilQ$x?Ip*oCnj<}xmq-nl%y2Y}Uv93u$IMJQ22@sUqYJOyP{UZ@qWmP2s1-gCwBWA4qHy-D$SX z^`83n0;K1~qm7eMZjZEwt|0WLbJuvqK6sNho}xO`4?0ii_b5!YP`A*xV~S}=3!mom zB=>H`y*nipH1Qk)A}sqN+@Frt2$-=}wPAxpo}iH0*S!MYoU+K z`Sj?i?}s)MX1VDvL_25%W2$e6JI#2pw!TACSV~5H|FF3ay3xpP8_P)%z&V8_J_Nsi%qHqZ$I zq2dF2!Lti;5i)V?9;)`J{6y5%ZE>Vx-{4D(dnI?)xCu*-lQX8!Goa}Zzy#(Uohl|pLC-t(h? z=Ib9!r_Kpw)*zbmljDc-OYn(OPN)@Hk>Ke>AkS`|tLuO$gKmO$w1dH)C>au*w_eE& z7ZDHg#^~`Bu0S!R@bvR14)n%v9DI(HxyIW+S!t}+<1e`Y=C@`;NN9w2==+)e{kzH& z7FPBGMA2M(GmB+bTq{AFY%7*2J^$6L=)LRfu)HeV2;_}18EfCuu$qI2rQ3-#R z*(Pis!q{V0L7i(R52QXGZ~bh-^OSU0NlzH;a8+CqXT+%%}djJnWnkkaHFg=`qLK$A5VjLLtPom zYeR|~@NOqcY&km>u1p4JANZcoT3(IMwQm|^lM2y4xdpVJmG7e9qGgXg{e)5dno|K? ziGat`5;VsI0SAU+w4KF%dch>T zqP#=X32KCv!YR2Cu;kgIyTE7j|*Ie(E=V)CWVbV3~eU`-VqG@crJ21Lq2}HrUfAoR3FV5_N4pZMEhoS6m5<;f9fYN-onG69={f#GCPp83pKpgB1a<0cwZdlHL2eiQz4 z_YB4Ib{Aux#)JvgXT#Ma^|F2Amz9^}l{*_EumQ?br5~&}eAyjg#TohL;_EKtmv?ZQ zE>wo9`H0T?eb6Oa*R>iSb#@J-f2M6GufldAgppLlv6d1cR7kdqlpf$1eq?*~CN08r zix1gg_83j8BmC?Y(^Xv2EU7u!-joKb?G~iY)k>ODY-Gs?hu5F-mMq@6Ucz!TF*Imq zNbNrcHbV6z5QHihNw%ZPB z7F#WPwKn=D8^bEyW7h&U`eol@<@VwzQculbgN-5ZV7HMNhGK{0 zO5I0TbKmwckH47!&?C;GG~WB8S)h@=RfD@5q||2K%#%puy>Tnl0d<0_tgM_W;welwZdO!uN=omnmmuJVl{|!ldS(!QmRLh}OOQ zkfY5~9)T_{B79y-)0GfDmEgN+FCCzuTYL`a*!Qlyt zb`mAgnmS}dc;6y&6xT=Y$q_8W-%nO7#GcRB?=y!rX^mzf#2rmdxmH|IGyn2vbtGX@ zGX-_tR=bV#LrRuKubwC{9X~Fw*z&{<*05&|7jhwIo(AT$En>SpyuB+;_TrO)fg()p zN5S!qf^|yA%M662?kBB|WcEpImDh{`{d;P1idcj`dGIIpTkntd4#L$A?y^WaHfCqR zs(8v?ueUM8x?CTbFn>8HT1_6bbsoEd;$#>{QHwx!$%}Zq|LE#c_wm&#`9={t9xgi- z`IzqTSbVK!o+OnC7CG=xsMb?cqPAQK`y){=%16*ioBm|xeDuC&^6(oH+osN@6LPOt zLda`KAN5MRdAV(LH$I2AaV=woUuh)+s8s4-g&*ub+5MoUVoL#9bWcE4WLTIYCoON9Q_>h2h!<-mzi0Ak^`U z6{H!W0(IiohqR;Q#u$iFhZE<~)v{jpX$ow*sCY@{u)4WaNoNV80$JWI?iX1NY@wI<}Rw zIi}zqdfn!+>r*a{p}Sxl{?@B61oqSY~lP7$B_)>7$UMCAOGL zttBXY)g8x&yivfH(nrM;K^5;b;Lf@l1F`;^uM_cjdVwT~e)NJD3OwX0sarAc1g#gd zEz%q)o4aZk8|Z?hSuJ9tM`@g~IjU5}vJ1#c;9fP<3NxHMBd!r6yY581O-pD$N%Z#T z-#@|86nYC{o1ySYr~OQjcn(FiF(N-zCqD_4e>aDdKlifPQKV-%f z=d_;ZfM6D11r_4_$Jwh`ccHz$BQT4{PV~O9un+zU*XZQ;mTWf&4n2l7P<~?Q4>1;Z zLCmlG*gk&|LCij@>3fdl2GE_&*FQ0))HqRZh_I|nK`D`RjiAb!Kz4m0(h(Wstci3M zuz`styQu2Fph7c+X)=v=o=$82FDVMKE#SRlF`D;h~dNT%pgaL*D z1`7)k2m~Vqt8U6C+C>5b>!1b$Lj~QAe>4RNH4#P`MM-9P88Hb(RS9)9C@|3W_P^ag zro$GLf?kIN{T1T}H!L9Dp#O8DAfhNEDWR&yq#*gXt{AtUi=%f>@<1jyx{{iH`u{?~O&HsFuC>kBeZlJ*D0pW80FtrGv59r?q|G(qr zf1OoW%(O{t5R^73fPM_qW12sPQw6E*I9UE>{rn$?oce(V76C$I`(a>CptAOF2lnSP zxK!t=Y5@Xi1_g@H4?tRse*mQJVEg|Qo*PiyJaC{mK?Hr&f4rD*u>2nNH*@#B*7=Xl z)1Um8^S@@w?7QpYZ=8QG(*0E~{hO`w{@(e&0`4~u-)qwT7-hlyKS2DSnBbpkfB$@C z`d-KItKi8uyB7Her2kp*_GjGh#jAe2XE90tfcs0qs=wDv{2AwaC7-WSSl_Hh@%K1? zD2(+p==b_EUqynx8KTM$p#P~m{E=kP&nVx^Vf?ss`>MZ0`A@s&|EOH^Gw%1Q0AIy6 zzFD5;KjZ#ZdgEuP?`agj$_#unblrc1`pxI-d(OSD$9UgN!RD8K|A3P5=lA|S5#5gw z?rHZA82>)X`Fk$EpK-o#0scyB_ss_E{|x6hll6W3?AK1>Z`R=dOMt)YEB^VNf8X2r z<0{Mt{MzyFdvSlp_`Y8KwM+Dyr3C#G#&722`zqttV)r+r%KoL>UzWaqezV^f#D2VO z4dnjP>p#^ie|G-;q4w9B+Bb8~|F!c!sIdJE^8G31k4uX1`j;Soa9aK|#`l}EujirP o%n!7o`Ytj0&(-zc7=Lp*sw@Wu%FMyQ$U$GLpnV-;?bqM_A9CD*LjV8( literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..04d7959 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..249efbb --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..03754c4 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,112 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel + +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/libs/mineskin-java-client-3.2.1-SNAPSHOT.jar b/libs/mineskin-java-client-3.2.1-SNAPSHOT.jar new file mode 100644 index 0000000000000000000000000000000000000000..be3b80ca985a95f2f354977a60dcdffe240b6f91 GIT binary patch literal 87826 zcma&O1#sTXmMv;#W=_n^%*@Qp%p9{FGk<1g`!h2$Gcz+YJGK+k&3{kLyEA8Mrk>PN zbxE!2t}WHxd-Yl^C0TF?I1msR5D=%dANnBwX@doU0Ff706Q-9|kYN0r00B|@+Y|!? z1_tK8HO2V**#Fm5URXg|LR?jiL0;lferi%qmY!iAQI?)&W@@%kg=vX(@7RSwMxIVu ze%`&JNrj1Jm35AFiB)axj!{N#Mq1rzhLL8BQHBnbX7%X!;27+0x6m*tuihi#e>)NT zd;Bwue~q{}^}mi7@$X$n7fVKaYX@^zTWbf#|2JX~5aGW!|KIlgZ}q=46}7WAcW@JN zx3)7gcVRHKGj?@t*7EYzQ^)*tXi1YZOwDMKUUat-%_=^3Ym`!jJ9kS|;FaFAi^qy& zOj>oz9G6S?QjHK%chc;`jI9;viFqvMgl}=HA&@9U+>r&JQNT{qRWn!h3k?Nc+ylv`!dm0PbqeLk!WOn2c zi_?m-(aeHT&0~}9D5xr6`u*@WDu3ZE0kdzvkXHUkl3Q{AS=V5WlsSub z@c^;&1hv6Ip`LD$3H^%mwNTw|yWtCx{6Os(STBFZ+|eBrCcYCu$X%+JtuQ>+UdO1f zHauI8Qv|ivi?A~3-Xs|Su;b07gD7ElAhTPT86wqkV&IT=(uck>!uQ%#$&gMmpFMu-+5Z67R zHE++c8do4UN%D~$QGR=?oYyAPkl%4Jt&SwEZ#od{Zf5W zQF}-#q0z!6kc0aL0@Sm0Q6NEJsdWXRF?XS6DZ^0IN5u$DCpC3&;HZHEOt*mjR*pd^ zkL{f&X=~=R@;1FpS>fo;ZFAE?@93!31GtUZIu78XXc+=^_&KdkU%ou!ESb`uWJIuV zwJtQ0{aTdCUAyMTlrZU&81+WQxs?tQ1CA_7 zlNo@@U@qAeLN@{tebpqMYdo%@DeKx=T3Nfid~;!SPd`~90ZcU=q|xs*Rp68( z%~g^_?sE~AQX1&w(VoTcr>mc90Sn|C_?e@yvf`_3=&G4kX|JhSYG!G?;S2@swlYd& zpzUMUW{B)AJw28tGgtZBrzu_$V44Iu;{OeNO+@i|RRKMkyjE_T%rM)gyga#*)uJI= zH+89_w7{r&R|dQiNv` zKBq-nJ}>!pl*n*RQk@f8E5^3oS3M&iSk5oDrox*f#5QfbB%73YXyz=2&k$BCh{5xdhJOj<0h!^T7=@*Ts{4lMHSV_#L$nfL|l_3C5 zjn5GfMJIwf97VN{FT&KZDwi{X&4oj-V0wb#r!iz>5QvY)$SQ$@$yxE!DV7q4AS&jl z1~G}_M=anBcMP4L_Y+Ss+{wm2pmcUF%ad%GL`FP=WI|n;xJqu!dWlGt+N|pK*)z|mvKYa`hQx^g9yyb2$lo5+ zMuWb-v4Vj+>Hf$EgR}{|8bb}kGTR2uYjEdKJOs;jRST_;5!mkOQ;grP`D7ks2D1kEzw{=$QQ+%>c2l%M*tO(3$gK{f8TPdG_{KfjWn*PR!teN7$USj( zmBwFyiwiN;eE!8|6S;PJmHND+ev_NoMq=mIPjtuMKPW0p(@uHl~aw7yG&(@W;S3 z@WJ1h{Y6~Uj5e*AN^}>SX0Pq*4%GS~GJ(RS2T)cW{SbPaWHpF_!?O{8TwR}{(@{Sc z*v6sWX_D5??=+RKDjOp{Y`r5f-Z+y?I!#Uf269aVj4Tz-l753=7riVH+nkW*llYAU z?F+Zp!Q?+9*1*qe;1aL0oys^@Lq=N8SChIIa3E1I5Z-K03bHpR@BjdDS0Q~@LC{b; ze9JPPixlw9yjL*#ibX|c{oC*@Yhbk^IInb_s&=1QTZ&OY-?t(oFTbt`61dB1!Kh!9 z%HCiz23fXX)i3K4+~$O%&&aRC@PWWLPw<%d+yMSu|xx92J1-iw(XkxcEIa8|&O) zs%$`xf5u9N_9c-Z&qn(uP+GutDh*R$+0Ylt zU11)Jpld90wIsYT=|3<--SW9qgawWg4;f?*qI)K4CrY5Q6B=8-24DmnTu@j{l#cN$ zHYr_L-q9&O5zL<$r#3eXoYbvj(d#_pF(}_zLYl(;(9|*mC1~8@P|2zZ0Bill(z&~D zUFYXc;K3oc?u2`^`z^pU$}e)DI~#-1;7Hm0f&S!=EJ}z!H|5j3+}te6p0YL1}l}%?X4H&_oQnVj0lmLPuZ!132T}=x2l(2&$tObdb^SUcxK%x zO!czQZ~uS|ZL&LpCwLGL-f#aI^ZYx4ApUm*A!+Vl?qcj_{x2l)F9=Z`&+jlGgd$-H zy9Xj7B9j3xG)UA(jMe}VTP)U=Z;+MHY{q|ig$yZKv?px%k@& z;wLTwi50WwYRORwS(9MmD;jL9Q#w`T5s4Kmj{UHL6M5N@;cqPXQ6noq18L6EX`QjY z-NUDTle^U-caP1Bk$bZ4j;^FA>`XXEIjQ}~8kvMHlO*G!;(tCcboSmgDdi(8Te*fMTu`m@nmKrS_OvscHgMUSEi%t zh~kOhSSTTRE+1k2?u_RLHQYm5ZQYW!Mx93)=7##!SCzrtXvV{cbFdwQ_kxRA^eWcx zg=pH=$3!Js&TApPyQSAYisEF)NfBm6vd+KYjOd)9n5&5ZnS@~K)mepY->Jp&WHR0I z6yDU^sm-+8$PN8OlZc^C*krh&3Jhp9JzmtyqwUY@Ml^O%Ki3mT%v(q6M4 z_Fah@Z-yp?{byMeuAZh-WjFnX42qCmKi!~H(jRk!O`joJ8kQg$NDp@3V6QNP39G>p zz`aYt1W?NO#T4}gV{7#eL{@Aq(&u7MCI>9n`nZo?vP3oU3PZUj`bVI*JC&?<)ygDy zQAfWk`Fi({+%z)Er)$`cnOyD5v+fqJ?@K+t%ilo<$$qWic4&4kzta`T9e}gCmi*Gw zyga$fhIJ}#Rx-(-;ec({MUe&2pM<}Xr7GmnDHr>dW53m{^mPnA&XzNF+5F;Zu}j>4 z0pB^J6~W++?r1fP$*y{fo_O2XacK{Mql`XysgLKpvBIo#4whA$JgfOVN6^ zuGf0G+;!iFp)Iya!%83Hln_=Q?oagIw1BQqN^~zZnUibKK3d$Br|{GX8fN~dLxQ)c zoAVdcRf?K!fqIG&YEbk6aSod%>@JC{4@z9!1*n{i{C6h^^EbpG#`7sMiM%G!MZsx3@hXCUH_pZX+q<*I!U>|k_Jw;h3@ zynQ9Ga)OX@ceH&6uRGwncYRB0e^5wkQ7`+lgh5($?v|i(Ww2 zWjEf}`bwamkp#+z#A<1>6kDe?HK`w|>v z`rr#-{SBk%D4hD*S6V__Sd?f$@pJ)PizqP2RH{?+5NWg`5JuIA*7DdB>PdB)L5liT zS!0gHJp(*YJ5zW?s`qbZUw^)Y<@$#_$;7l6yK=qA5DAGzy|%~U9!_-%ae#y& z#CK3*Rp-`a`_lb!uaSKGkC{6uS98{yiJz?PKtsOS<6WYZP^eJixBvIb&+v_E-T%~eYF4d(iqu#QK>qCOrY0K#QS5%K~pxQz}?(`U@Im%LY` zh#1cPcY7jX+@`>*B&8&YK}|OBX|>-Lzx!TA$$J{ft+Z?FIK>Dfb#CGd`XA4hKi0t> z1pxxm@pq2tf1W=g_;=4HZEtL8uI^@S_b;Cos;aMuu8hK;cJpJh1q0Y59!2sh9@s$g zknnmBQeRRc1STSq9B$v)1aH4er`zx056jqd0WVLs51sxR9w9v2Elw0OFK=-(GnM0N zVPV;;@6Qi?M-WZXfx?nMoKH$O*J>G1SKYB)rDI#nUrGQIlGiTJ=}C-&H|u~K@!qop zx7E??z)5Q`7(y&u2sTJ#_6;g^v#t`*ytJ|H?pvx7p9+i4pGc*!bT3j6znz%j$Gj!f zE99}r4fo(ai-e)M)Av*89nWdK(x)d9LIsV4p7`N+SBTV}1%l|YjqG?&k3$N}d#tk5v%xe!|p0IFr?b&4jUn305=jV*x=AAv} zZ#7M|**Z$D$PiG`0pUJ0D8H87l4Xrz2rZ+(GLcn76vtI7lF^Pyi-ow+=8(5#luQ}f zN2^zk($4oL|9rlage+_$-Cln=Kifh4@Cq3A4_Hob-*0|zNb)E~?RBuy88E^i-NO0p zCOno?KvZmgkHPmVl4A%Plc)%ZwluJFseT4>YtS!u+w*65j#+|m2uGbOlxb(|O$uxJ zrYLT8?3#_0fvk-vr54=ur8K{5(0aM*6GK=EM>60jQAb5k)P$E%0smYIe_RzI*W^_T zJI~)=aHVY4HBTBvMO>a##y*j4Vms0pho6obApK+l<)^hLP&3~;zNU*%cCcIDC!Hz) zpv%hK*O0%P-rE-b(>R3J&sP#}8cf|qCW(}37nw9(?sdI~x(ngx!1Bcmo!n@a0 zwjo{R(=c}R!ngfF9r7TZW8}N>y#3lbzU>UT@32O`>F2pK+`BJ1i>Gdze)R-%Jbp35$wax=NdGO(#H()n|@o88@MfXm3-6b?7Z;)&3m{Zn_L!z ze`XvJ#f4B^*9X55jaj6`Bt@@OQhy82ejwGc^;m=y7WXDN)8J53^r~f-Y;<;YAu5+Mf0F&YH3)8)6SEFPyp#~=bFP|8*XgWZN`HkH$#ON!eW`3TGam3y?#Ng@{2fRMh0J# zB=65R@$3m@b&A?`U#R1Z{VUC+woE$**}t%i;ZPG9BTUyFQU8`BYl;o2T?KcQm39Pj zMM!!@^&L-(2D-qr*t=&Q5S2pzV%BMxwRovQ#uyUg>xjM*rrzM*V-}HkQLfBS++>`{ zvj81tZ8K5UCU^!F6$Nepa1)!XpCvrsDz4AEDi7TsMey^J{H$gJlqmKum{P)&j4IA0 z5D5sA5yEGGPX#n*=YLT)-0#D7OQHZh;6Q=%0A@Fn?DQLB5cCMqVY&|<)sZ2B9nd2= zD^nMWrQb(#XOEK^N;vVX1@(}R3$}r|8V@=^WviY;o6nu)>@pi7p24|*gpUv_3+ZP9 z60+*Fh_Hwg4rMiSO1^bi#UEg@Wb>4knEzA{WY%vx8rXI03z)Ns@bLhU@1$=;yX2MYP^C`|IyC@}N8^Uu;e2VcBs@0Gk{Ze34q zO)}B+5m>T`Blna-ndFB5JJ%)mF}PK*{;#2TcNQ~Glb1EhHP#I10|aRsw}pJeq-Esv^!7x zqj(Xuv%+dRrOJvs-{-u=6Li`f@n|k=&j|iL-BR!!%nY(-1*38;(Sufe2>< zkW#X^K%_d?74+%gZQ{%7kX9$Q3Eeg|h2}oxLw9p|gH!)Fm{ZyKyL;~zzxcJzEx^mX z?O4&vwp^{f&l?7OO24tOI_|vm{63kk`sQ^q1P;Q0R=GtbTpq?kcwB~3CSXLsrgJFa z(#Fo`DI{SZ7^zjh1~YlPQUX--bfBv#K9}ic6S64Vq@W$--<= z3ds?IMOYhqYFKlqwuE|TwFL|WqZNfT?ii1VpD*Z0nY8B7$QKskH9~|+5=|8{El`}Q zLmU~+u_t0XKtQB*uM$b>>j+9%Nw?P-ce8ck$#QBD&SxPcOsJR3UfeveWyn<@!bOKC zNS%+dFD7AepNo-!bZrK(b0v)>D3l6aqLmt7UAk5MC5&=IoZI*%S?L|)gV|hb4TT`Q z?4kj&d@ZTsMtJwzEDkXqS@&%jC;int9FIo)y;&bKE6zwWdfV-Y;)WDJhphBExUv7~prQ&r%j>e348UX2v;@o_J#RxxY36yAioX{s?2~+}W zX@0mT6MbHuRHRG31JdDvzH9~3tX+&8BDg;ZxV|;oH-K=37MS%F@Dq`#!TxL>RhW@6 zFh!jVJEP`=0r^jz;ovdPALj3K4H(CBb{Nd|_n&DrgP6aK)I5-O#Lii<`WIOPcD zm?}tT6uig^V7X1?jf8bgSpjaC(5Yjfmax?``%HyNvSX6b&^j&cY1CY z@BMv$KBK8u#Z28y1)Zh2bgEACzoH0K?UVA{jPSGF`+`e{i^T}_wF-UYSjHAJ4+8OZbpz{Vw+4+Ente#p% zzp5JP`6V!1ATAQJ_nB?)^oDmkE5Jok`$BGP~ zv3&1FcC!=?Smf6}ePWV9?w1K#!V#`)B`bMnQ#;m+19xho@?a{nOy&%0&&o@Nb<&uX zA_cvQ7RT}*zT>G^C5z*WT;jdF+hvEFA7rIChlMXe3>!~mhi6u;%qLYsR`cleGNufn zahcZp*^TiI-p-`VIIJrQFV)*3(cH7tiK`oy8QCty{M)j+6=kXkFj?FpPS4HW4(H05 z?!_*lXH(*B@pkg=o9>cTax^r&@?je6MH})6i8o!Hbdw63)TULs8>AX^`ms?JF3KXe zyoG9`=w)SC$B)U80(fQjLTP}2y}acCc~1Y`!iRFK4m@6ug?4!ib6m;tg?mjt?O4i6 z8nJ3!I_y%LLIvz!2W)}ttOgbj`Rp{hqEU7-6F4k|P52|f=>@-5i+;}&meN7{#G27D zEZT~uvS;GzzDnrqt?>#_-91ZkLyZZ2+DaE97Ft!rOQJ7bdIsg}0sv{R6SLkW@ z<+F+FZ1xM>BFvyo*}H)$bK9G-I-jd(+T`zFB;G3zf@VvO-oZtilP@VB;5M}qu@{EO zz1|K#a!>cber-iYFExVuoSl>Gy1d8t1c>z#iQs;Kc7K|pe7+U@N+S|IhH(1|gI)Tg zOQCeT%LO^{1I(ahrQz7r7F;)LZDU}?>$7N$Cy;P!ZU!;X2Xo-t;tPf6S!X0k_4g)& z30roBQr{I7iL5gp+7)B$edGf=@7d>lO16!>;n2JT%byMD$OUv3KrwB>QAVW-mOteD z+(nmEqOrN`pNRDMmlGEgmoxyATV_2z@X_jQU6=_8OdH1)V(bcv|63&H4J)dCA+_PX zM^(9)e`Hp{y-WQ5N)^C7`r`FwX>x$xKvhF)1G7TJyYF`7XrhO>wu7vuyu72!x1SN_ zl@vCOPRXAJe?WsiIy^Fzp1l)^GGbmzsYk(U>UbbcYI~Ac0sAOZ5(FHwXov-m1eLjB zq7HfiaAr!~7``*xk$c&Z;_697wkF`TELP}+_^lOKwXwicONw&+x3X3cNWX(tQyB72 z6p*i-5kESXXW5-Q)>in1lgk@e`Tj!eM62xf?Shi|tml}+jqBMtW-LcOWvL-l$EGws z9~%*9JDLSJ?2zt?!0Y}*_vE&R-e6SqROfzH-Bf>>a*J<1hw-}}yDWY!j_Upu6{&E* z6rp}rn9Wc^APN&d@h7sj(h8h#z&xtid!jGS^aAD{8PO8mb zB?XaVp`UpY(Pa$#u9KjyLP)cR6TB z)wc+gmB}=<#OY9}#we4-T=kd~4?7tenxq_?LAau#FTi+)E! zq6an=)Bnwe7qbkW1OgX08*PUZ&Bb9yUye5kr>C-BJ_B}q9xZYtzdR0vL8_Z3gTXLp zoXV+0n2qa=0Z>Kz>A7q807&_dOki$Z(8se+5f(n+jH19(o(rpG1&!ma^Tq0|$w(|Z z77Chpy$6zl3pQuZSitxdVGuc#1%rhsBPTOO7acebgR zEMso^SCRJ=iD#(|8vKlsGJ^)~%E7+uFI(|dIZT5o5-JU@3Vi9*VupFc@hRqa83+rBgX6(sW<0YhzBNgy+~N~wb7lnh6!3eGO@yt% zi!?(E)2TZ3M8Vf(2Pi^^Dvc3_6n|RFPl-HYAu|lXLDH&M4cLgZ8@b2b5pD*rUBshC z*9V3OrRG%L3XsoPC?YhvrWQilVl-7~MMuLnHp(9$MqR8pn5H`=2wt+d^Skh+CH@-t ztr@M66(!rp%f`xw$11n)gXJ@@*X*3*G2Kf#ikCyf0XGh(>r!MsyeYrPgl^)L! zjHbUxw=aQQVCR=8&prsvK7V>FHcv@n>^fqgc)Km4*&79lz{1$+Zm)H9mdR&IUa3za z)>^g}Wq;L8;)qhwP@1T6)u#ZdS=NT8iF#tW9qrGLdP-%%p)Wde*W6Y9NymhtH+`R4 z9;#1m(b*0y3PX*fQ4kDn{DZ>><_2{!!Xa@wrJdR;+A2~EFHeCBR<2V$q&|Faf6J5{ z-F}2g*YK?N7A+VRQ@IXom?DdHaSB$5#m&2kYqSa98FTgLOCgEL)#@}#X-6zN82e|; z?~I4yx_GrZ#bJMf?@N{hI2;B2uomWtY)QnEDCInC_t8!{y|kwL)Nh_q`{kxCag9!? z+nJGaJjR&8ToGwhp5;-OcP!7R??X7kT+HzZp-*BWi9MqIld%14)*nJraqzd9WDJT` z&yk=7?)W4u_%pApMF0r<4vOU|1qHg9R zqr7v!OS=_Mxf}-jdTy{SYe~rK;pnr1t_Abn8w+nqHhgnkOjnBPyk~~|rg;xbU<@q} zucBb;3zD&lbf#h9u+M;0S=6T4??(eLrjyrz!*IR3)JbOIlwY{Pw78EZEWioxQgRv# zM)wrzr&RZaLvEPEh~ywen-{m)x1wu6u-

  • d9^`vaB$&qrA6GJh0lhX zn$td+#99&6Q*vsrKs`Qej^RAZIZH%|5(xCeA z$%dMDj56^Rf#P$|kGYGDzrV4?$#mAw@UAo*C&sEuK+vt>G{jUSKbTn@85&S@0Q;W09E~(! zZt1iRhu>eL#b?beoMQUu&zSrkSZ8+8FBm(O^qLeTSosS7Inh!IyWAXo)t4|cinrUu z0#7qKJ=}b7OY=#bPS+gcpd8X9UF){~OU{e)R>F~m2bdL1LLZrxgStSX%f?FQ&zr+w z>ya)Rp!{;~5J^u!FP${Yt7xTCZjeIw{j?fX7XI3t3qaJmR*u*pl$};7vk!xkOR&n# z^YQx+?k=CUxc-X!q9Sqb1&69~!yTLO05vnlJQC3nA3wQ4`t#h;K-E41nA8J@7vowh zVJ;l>+p$wv2YYZZy{(s#*QZVh3}Z`+cmdpx@EFK;B>X)e#MNF3+is6(qer!GmyQlI zuF!UmE4kJS^}{n@D&1z~e54z%1L-@B6nRG2O%m^x>_QKzaL^22YdlDdjNdc@Fm?w>q&Q3Z)cc**U+K|gg$=BOj?L( zLf-*{fm3TqEnroWDxlXF+w^RvPL0!vggRzfZt(<3>}m#b_^)t6_B1(?vNTrGUa;;?*3vmN_89KPS#cTk2b(OjTSo=5<+=q#m;x8a zCg;h_`)dNGwKr>K0a>?mL!T~ETO8}sIguQd9H)^T4ufl1F{jU4Y{JS{W*I%KFO*1@ zksS1BxG=ij@S+=61(Ril1)wQV=PotIrBgSlNaHrm39v%N^W(ilKKuK}f>xDN^jXnp zJ#_BQ)8-ReEA0ccxosyMiuwrAW^B|=Nlp$1bC?~8b>Cmq?m02JahrX~=|PlWYF{tW zTe}W!B_6Ja>HIr|4`$8Y-zmR3B6Ww~bFr?+)TM*)JtVn_2KG64m2O6NRbQ9hns zAYTWTn6hB(T`u%AbucMfG3{l8z3m>=-AJFoUtkUD!`{*@A>@z^WFOXU@+8i!Y>_$7pQptGJvM76vmnI_n#N(-9SfTAE)er^KfTm+O} z->iC-6aVa)SiE`KzReA0I(SP8^_1w;KoQy_N^W90Z$@6}J;LQ{-t@;}o6bJIZQ!d- zpQ3~;Cy$R)dTeL*z1?Z$K@GDNWqsxP@(^KB2uSZUS}=z%19P=AL8J*A_V1{XerGpc z9iqNpo5Qu5C<=Q}{j;`Rjs$~Q3Ill;{*~JwEs-~eZP&zx^9dGdWG^`_H|Ur)Dt8m0o7yQbCNNC7>Zjnp1_~pda=ze{p2(|kXkRw0Z zZv?9SF)e5eqxn#sqLH1>+;=jJ4ze7Q{L+U*5|}JvfOLT5#h}qN3dGnFW(_S$dL^A_ zXS$va>_0Fm*P%Eq8gg)rGdkmXbryWxedQve>66~_n@F;dLcZNUJ2T((COe?e7AbyS+JJsSz+kCX@ zF+K0*qwsAHr2nX?YjQ>q#2Jl)-}BpgbH#OQxfTaCR8G2UkRI7QH|LdEbEc_BcXfhX zbU6k-EyRQUQ+`syEDS-xmMgVDkYUUEkO2#&{4irGhEdwcbBw(rM6zOMC zKLnY?gKQ*l{o0k2CBpfABeYteHKK7BGa@y%o@|fy9`h}kE#8$3B`5aVJ_1)%=-Tu; z#T2f290ZREtt_a$Jg9xK4rN@+0?9uolZvGKg$cH)M2Hp{yeMkC`op91ly|Ju6v&Z#$)1Ql!LVLJX+rEDbI&qb93d=7 zj=lLo7soE3HhV8n422z9(nY=uDYNEFqm2yt$4wj7%}%m0dROlTifLTcKOF4$-LdM+ z4y?)~iQ*%Ez9z?k{?FS7XY;EOYK)hNe-}cdma&r2p0K()LbvWdBuH_s^w&Ni4dxy^ILdalib=DU$3ct~t(y z^P8yUjkADux>QCgaBTci#&`T#Y%Trj*!FP$X&ymK`1i(aE0Qi z$b3r5U6{v8cOt-_y_~F_($7+yFz*TL881CAguO5Nx5qW5$o`0Z877*A5XE?4JQGR` zTK1G-Bt`XY83d8Tq&dFl$FfoHldgUpm+5XUo4bnA60b-+WaN!{Qw zq2jQ70L@v@oP%i`YJJSB641w}71w>t&Yq6Qbp=*taPp0P3XLvrfX&z-nqldOm>Ky!7WOOQ`?82Tb|1|#Z|yyJ5r~- zPV12giXvXLZj3QgQNn*_cO{%A1d@i;>xmWtDA*L8hYToDqmf~o_`_0IIz60y1_{^w zH+V9NS__-QP~95VY(3;O!88glVjZl z!$@{6`N4CZnZ9U<=r}a*m@2@{bQb3`3?QdTF_oW9%s&C?(*>S(KB^gSW~m;@az2JH zLc1 zQI9IjU1FWGo0w+)yjg*^*u3Up=tJtiUsPe$TfiwEO@AAN91xTj!Noox$NO>NNo^o8 zOASM-&z^yY6N@^dzi&OwA2n2nt^$d$($iE+QDs8d9OlJZ@tpU|eAl)8aq;9skAS9+ z&0R((z~bZpk!rY(}$m8?89 zkgh-)tvdIZeUnxoH-GkJM7u(Bat%-Dc>X?40)nuQZ<@TN{J?ztLOpbvndPdUxA1p| z8}}}zvEu84Y-DI|!>CENt3_w-nlYqiJDZjI5NlioySVcoV!CQ5-6Es3%PK8gGh`dz z4PsZVJgWh#MB?+IJhO*lcPgyKXZ={Vj1lKNfF~tZiWy5sb=yXz5-&_2%vi@(su$R>6pA zn!F+>t?K7@jZgI{`dSwjclJspF!E`Frq}~Wy!S6jt=h0F&!!8@B0_ zNEXTq=;g1liZ}1w5k1acp?b!bltOB@vY2_#Jrz9V1(-_jC$c5npgOP`XuGM;*{^DE zG1#!uDAmz4ufJN|w?c1WPLMk_ERtX|U68;+hbmn+J=TA8mW*6U`FND1Y1&`EsO!Fg zx40)2Y;t7RF)CxO>wky}n`IsbQcgR{uw>u%$GN{lymW-qT8i9{1R*69d12Z(H+#S9 zjrzSpCdJAST!diBj2dm3xnG{=5AMu9jTsO}7*+~>B5r%I2xC?_H&590uHHkxCrB^V z^Tsk$>{H`Lh*n2Eff5Fc7(z6r2({i`HmgQbEj!Mr?>I8Kibb! zzmZIf0!_J%LsRN-1v@-CEcgZQ3c~F4{QWrQ(Ca8|3&>C5qQxuB>Zp={^H)wHN)s9> zj`hfS#F!0vGVCo4wG(Q##9~RT2u3L*$a{#-%6(}<$)#W7_C(!n^U9M7EPnhs6zLax z!hGUOVrnpItjv{I5ok##`4q)`4oB7g27|+HzDq>0_k-8gjnI)VS4avT#S+j{LmcFp z$F+k1JdNIjh;qjOru-X6h*E*9=eV~mYo5X9Jq=Rhn9M7-@$wDZ-PuTF2TrxY=H@;^ zk(Gk(SN|M#=9E*XAu{&hBn(mJlx<5^v#9GaSPPocNlXlw6+T4f%|x*dKc0H7pD^~d zrecz3cb_}z&m&<6VPN7;>#hio8(_u>`uIAl)Vfd$FkJ_~+pMw@7}hB>zP@;2L;g#X1`G5t+SoJ9XSBak<(_QS5o9XGb5BU$TLQdrjW z$Z1o+Qq~$*H%%|niUy28~Tzt7^2PU(f%Iq z*)gtbS(26Fu>7X#7niF~am{BihNZtUW=(vaUh{2s9kk{~rLxmqo4)k!()ZVL(WEpQ z(l|$o&1U0U-#L=ux@*?&v1@{82WU%8sQ{F4b6!O@m%#ilulW)|GDfVfi_j)EM~)1A z21eKk1+Q`n#zoYG=rw=>Q_S$o8fnRG+)jW12W~~D#f;DGQO_>r)7B)f3MD>|oevp1 z$A_`egorx%L%bo^2Yt+J;dEWqPP!>g5>yZxX3I_qL#LUPlL(S~c$PcW%32CXnT^}S z>h^4}*RY~DNvR<(Az9VjwewBS<@bt%rK2AonK3Y_nC6WXa@o-(l_hr0GnUtbUX8Iw5c#id%$2V(5)c#@Ui+Ob$irgmE91)U|E08`zIFOoqg4S zJ{P!0CrzFV;$I1A^HkwO^ecz1$dWB4TL$SxNAw?ago{L-3|agW>R=@u)>4g=PAR%Q zSENwSFhti35fWcgg>F=Oc1zA!Q@=y`_$(&}(?wx7ke$^PXFL4S=oibmCy39VG~2=C zuY}9pmS_$8F(k&^VQ|rm-GEt0u9BZm(G5Uk0`Wh2R3D%+0oe=RsHpgp6a4A&M$tRo z7pCdXMI{qH$(FbSU~_<=l5jG$<5GfvMvr~oo+rw-<0#EuM!(iXh1L2RaZLTui!P!- z{7gr2y}9NCg`UM$w8J$YZzKQwhs;Z*yp^Rl+|fzoJ@rTM5l}sDKr2-(a$84kUxaa+ zP#U+ElzplU{jbbub+_2RO2}{SOIu^qr#;CNBHTO8g@UHyy>yAgF*%`D_m*h~80Bf? zHIMX3=w{UB?C~ldq;m6&kNUM(fro&fB|4Hy#l&6^)1cn~=%VBm3Q6%!DA_EW1BEe( zl@Nz*B}tCAsw3a}+&8mq1r*){xdF4kowm8^wK5EYITSpLGbOUNWU#Z{eSR;1T`fO9aG5 z1JcKTqp}^=vb{QTA;-Bao3j1B)%%5v_pXTZs_CEa)SJy?nlA$R(**k*{1+3U;dp1% z-Ma?pFJ8!{yal1^HcVtV9WXEB3a_Sm~J9W!DZbgwb)x1*mI1eJSwWr9Su>}Ovgp5)uJ9NeC5^H+sL$t>TAFB# zL6a_BWYJB)Kgf_MH#n{7@2?urDE~KP$oBsO8OmF`n*Ix*|0h(aVXe9;f#aVlYlQKC zNPFktNZajecw*b0IGNbCZQB!dY)x$2w(U%8+qN^Y-<;<;Rp0sPd@riHtGe#$Kf3pQ zUHjVi+H0-7#~DD(4AGxE$V?$q-2gn>AJ|_CM?xk$r0Bl`QPa|H ztuE<{E~05H9%HXkuu?L&gz%+8(6pm$%UF#qE1WFAqC3A06heE7-a2O{Ti-GTtA(ynmi-=L@p7Tqk(r7LJvTx zhHo%pHswX(@kuwRcpg7Xk9yCi0Cp-OAsnN3FM+|K8Hzbw&fWLVCAU;7aS#4OqI+X$ za#;cM2|LnJX=y6q09zZa`w%iC5_nxSA(vm?-6_*vSHz(i>7mV>KV1GjnsBZPDLRQq zMQ^4=Gi{l^B6HQYOQtNnzL*v|r%07btw9-7cKqa|iDlDpq8oCy^^M_#d?hun_+$;N z5?=v}YPBo>_De1(8m-7qzCInGi&UxKo-osoxAsut+~_`BnBI*Nv;z(%v*gD)A6{+b zDC0$Jgk}kK^PII)>{t~_zJ6sOk*7?WuKX1w{lL{uVqKpNf&CK4MR?~kcwV;(Bw45yY1-m7b)`Y6yE#ANzv7J zUh)y-O7xQzktuc42U7Jzv;w`KOMxaY7sOIE=`B)cvGOpFF(7^_Hs62Co#`sRatNf; z#YC^8Q^0l(2p@ti!(@z{?@=QHL?7vEgGY`a>~?`slo-YVMhRI&S-5FpH_*P9l6g|h zd=kPT#m7+eGC{gq5|d=r7eYV}*B=B=`)(g<)ZD3Ffm**Iszm9b6M;M7Tljm>83qA( zxVEq$U-}T=4`b9eOynDNqBHyo2!8xrRPH@jTn#|n5Zw)07o6(W4un-VnFeDHTa^2^ z<-q70pD(Zr0`geJF5CBul1;`C2N>A&PSO(;+0`^?XeUJ^QK zdSc!me1A)2$+s)dIT1Z>(bCH2EeS|l;YDp_$Z7x`|n8DqTAO`*L~l^Y%Q`Av11 zAX>QOclAIXnCbX2OzPQgt!uy4qOGsK0bnpzz6mhrG~O*OP@1n5uM3|SfyW=k8Tdi^L#hDYfBrp0DU^QoaXUQ zS9S=P8g>3a*{lzXWP?>UIAl|abwH=kSOI7Rf zGPockQxdBH3u`?s-S*E}5Zwm-$e>2fMT1U#Q(l@>*qE$@2Or%T{Ne2^HFq^1HH+X_4pJ9$HtQ;_{{KEu@GJ_*iS;EBVy85 z>rIvm@^N?~v>mEXqK7IVd8~D1VHU|Cj}1HZ4Lfy*;Ff>1*lJq@i38{KGZj6*a1&;K z&yB#biw{b7vKoSSm(rC!$(nK9vW-!{tRPrghay4G2#_?WDIj@cLQd=EC{H1Hx0uop ze#mOxz-MbUThoOu$`1;d9PdW?!2<;%d6J{Q<)-BRHlAJC7)03f2CF-RbSOM$7Jlx0 zHA)|1fM=i%oN2cpV`GW1D$9^vl{84G-w&%7m&4LAmsfuwC@iEb275Ceks?EP9Wc?! zFcevD&hQW;gN&|id#NtukqT#pxmLkzW*O!eQ4e$K zpgKszo$vXg(G&JI;J6Da4~CGX6wyU;{L0~Hq&>2tkTZLc?BpqOu*&EzKxE{01FSoL z&4Nc)irQL3e=$N_#(t%Rwt?|r`P8<(i>o`bL0GVHC>w9}R)j&fr?Q~pDMa7Q8$8$k z#76bo6{z~m6+{da&0DMkOB_-!)~AmgT$k{sD9UD+rVhX1MKgiUDYB)ik%9@E<|wkd zktQ?2%_M~dPYk$37kzBJ#WsMI0kmc_T@HgD~kz#j492CoA#NQ)U zS?SC0AV->gHg*&>XwaHni&gstxoMYM3cR=N=e$ah%iM^y4<%m`p5$EctCJ@}?`&2r zsOriI&@b8#iFSWDUq6BQlM$YeA0OH{RYA8$DGVL=gu9V?Q=XBe`OwGrBojl}5$S#%5` zP|k?NE4nxSk#|~FNVT1=8S$=b?`&1>u+m-*^bjd_8AWZvECn@5@q5G+R4g4+E;Wpb z)W92rT+3%xJ0h0MB*HjmlqsrjqwswYUN9OU_Ac8>sO*ZL%wzSXOKfYEHkFJdt9MML zabT3A9@IE)aI4&jb&cTtiEXuKN^+-+Wp)k*mp#_9js=@qs3?_>a*jshrA@nN(lw97 zaIkk)F?@}kRP028kwHl@`iEy^ni!;Cj)bbvvzlwK&&$-f zK5mR;4e%T}jZTcL{CFu8%?X4?&2t2Z<61Wu1h428B{qbuUr;1|9OO2$!3x$1bkVgc z-Q$4AOp%}5VfGWin99(?!VQ#d5vI*z5vaSMa$Pnq3?~sy2@C`h-Z~D&`XFp;YFCK& z@OwAtGdF$AFiTO}hx*l^z15+JHJeQT*%ZB}-DWGohydYzGk4T$vgQ6EmjZ*Ki!Gtr zRKd!1MARm`J5k8d!K+uLG&U&9#OO^hVwcpTh}dLy-!I_TP)i^#$MGtPY)($)d0SGO zC$Q2{AYX~rI_hgVgog$r$GfU;*pbZxFVwUB9Fsf+p$HDN22xf>RnYwe29FMn#_bf1 zq)fVDf~fp{MhXU>;r9^@ln)xc@8(-sjL#VK3M`7JmDV-}rgjiuY8ZdgdpB=xv@x{2 zUg+F|7WZ~gdRg~&PiJOILG8-prTPnHG~*@+n1y1+LD}RGbpSsx!vVG2bHmd?m5$!- zs#2R6E>gS%P?~dwtLXUEc`bh2wt}DSUriKyPfLF+9$9ZJrQb2>nWweUoGePf$<abN(Byq9RjG8$@ zjo21?%EE01_DmJJlon<$ky7|~w2N(Ql#kIEUSE1UJ^rF)8<|M_gGgnh+f)jq`y<*` zE8eIrx{LrBx5Q>5gJv*&h-s_xNbG@G@j667;YYN`0hF6!Jl!!xeDTlmfFyRlWWcjJ z>Xsss__w}Vbjb=1MnKfB<^%5!a=aMt5!@&Q$vr%JG#?zTSbAPwfG zHC!rygp;qhnrS{}1ocDN0?!^Qv)ew3B;V;Gi3ODa%ZE%>tAw)*cb_flb1!HtZvZmT z-H$;j^^T>wgM`lVkCTpWtQr`GnL_hgYLa1OCY1kZkkXa+^-a3kla$#0ljV?qfQ+zZ zN?*bSUfC~IB&(1%fSWgp8uWTG@-^3X^G1$Bz=Iw-#=-}K0&Quk>0 z79Z`RhPpI8faFdOnasN%++HGp@_(zSc0PT&)%s)B_<4%|42;O%LzrAq1H!d z^mbH!5qV;_*=adK2f7)kd1RvEtriXimDY3fVN{lfUu8;!*pl)f)bf{9pP?;s@`ZUx z$4cL{by>!sPa9Fww27&96ma9fokoifG_e~bu>vGil*&ySBZXo3iWNhQmcJ!alALb! zquCg`Ei^{vt8ZMR@6%{6O}ipr{BmfvLroW}y%0y9_@T9}TGjxEVGwc(kP>L(Efw#q z$nD*g)Ek?^N=X%ap~0GcC5r(lyg(Li37inS6;_K&>J3f7K5|#7s@Y812-tIM^S#syJ-A%MYSCUT^q*|{22-HaMqx%w>BN?|Y8-!Nv2d;I z`7Mm#?VAak`TZ_a+iX#eC8#2W-meXvrSBu-k}M2({ot!x(TQYOpcoTI~5nkCftOavcU@^1u=*QZknV^mLRWglU>pKSS0 zu{cSeoajkc%I_ZWvoCy!i=R&5SMAUD#VlEo<6INtE!d$Rd$OXT|fkFWIEKYRD;-6%1=8-HUzM0mD~^fhx|hXz!qzprtB(!JuI@9We8_7$y9B zP&XvM;&w^o7Z}}cN)j@~3OGxjHC{a|!4;7-aSJOMh|tU?*Cvpgf(1H~(F_UHHb(Or zv&#WS*LeDyyeWS3t0an415`r77COkKkrD+>h2PP{iO_6sU64zw7z)_QTgBf~bbLo$ zgG1yv;NqYIm7Rb~2gr?s^jpcvr5EfC8pq3TNOt1FQMCu)SO%c0b`MBdvaWIywnzNZ z;)ut>7cRgaE~KWPn_7yDmD4Q3uW?_D0S(T8B*luCeK-a7pN>{ebb zG{^U;F?|BFA^lDdU3cE?^3MPWfV|s+n6vfBbpi3--^$uC+aYp|LgEIEZAloF&I9O1afsqq@1%VGprxVHD2l7{P0T z4VE~wNZ-W|Nuxb7a;rJvlb>axxq1xpg8lGOEZ`Z9_s+m7SeHW^Y0~bcWk3Z+TnmvI zR=TjJMnjB3a{cLSCmd+f4I3;)(54cghSQ0c>2`ia_{(EDS4d1uOAIC_Cj{T9tZS1I zKJ~E^?UY0uU32$6sJx3now%;#$?jxCR-2!2A`?(u(~YtRB~w6M@FzNyr82Q=u&Q4) zUAI)&iHkCriVtHBKm}EbG!hmG=_xeIy`QOu^-v+LEkR-6XOLeV3!p58F+*q8MTR2T z0T$|j{*^rCX=i8|%IPPejXZG6*w-YPUVLbEmNcB#Kiv>O$yw=F(K4tky43jq+B+TB zV4v{0Va}O#7p4J_g93u(F_%(`G+$U8;9R#tlKHiBZKQ^J3XHOzS#OV_qD5n$9RBLr z@uw>EW$o#mP=#A=3dxEF^uSDXD!uHxQOid^k*JzPR9Qc!6r|V!X`!BDb_*3VwFc|F zA#3sAv0uobrjP z#o1wpa|#`wd>)014Zb^wYSSDU>Z^6oy5@mH;}#K0%~Ee8@F204x9|(uWGa2b$Fvx<&(wZXH-Q0k zB2u4Wr!II-IbPETLt}ua=aY6qlHW}aAnl7JKjbLq_M5VCGs?VNWaMJ5@pzoD6?J()>KU-pe@4JYzd^IUA{cB53F9SDiUmLI7Px=*HI{x*jGz2lHF#5`m@Lovv%a zH(*(l+l9|b#v6dgP9A`#4#oRkdm6WF)gY0es|i!<0+pXS*uy^vLvqbd7|qi=)=eb) z8F>3h?me`>@Qz@2Be%nO7q@6`n07-$WLlIHjh9DP)YtX2(XbQ^Z#(`H21`rHi1{N9 zq1RT1CNri>b{q~F|(e6uc)C61a-t(gaDu1>F7Q&jF0LrG%cPWJAUkiIwgxf zD4B~*o09_P?KdgX;8px7!312?Zs*%7dzqAJPk3rwacDi-jV29qTqxAqE#6@bryweZ zObKTWqQ)==j`0?!ard5QnQkoAWd_hNS<{9)_q(#@%H8uY0m`p2!g%=Ool@Omwe84= zk=-F(b}!kN(QT|m;ybaKEaXrrN}##fWC_6-Z3)gh=+yM%Co+`wNM<*%*M_lLI`bKJ z`0v#~$zuqUlLIA??46|UUmGn4-G@*?<-XGs(I-J-RJN z#)b2~YKif}5_}H_9KBJ#tE_J6KO`ZmQ_cF@RMgP0tZo=B%d8BfkyCz_i5e`CRky04p|IrnbB*}mcYUy|H<>|KaNK=A>-^lcU@#g=n@d_+}PYtap*&RRI>Go6DZ`-;1m{f$I0p;1RL zfcKf%rFTjB8Upq@;3LiW%y@JA`a_L%6Rjk9+G5h^nbO=^H{7sJvkIFt7=gy+m%~Hz z%^J+3eis3KG!X3zT+gl^s8(LogF3|opRBy-vjm%*JWm(Y1Em~_Wad&)kItvqt!&p9 z44z{$r`hW7vpxcABuw&w0=$IJJ3l7l2x8v`eu$1lOL*snjod9Pr949rs2CKPp?Tzo z$(7i7I6ROtR@*j*y+-bVIDL^X&2*kpx0oHhi?O=dg|fOS$etOccgRd_lh=tYto}qU z_fS(?L@fXhphN%KH3kaUHI^{W%`#}uTE;C+xPOaUw+ZHbo!?+FnJO7MdjPe1QyfZj zva)%R!?e4uglu_4)HY73+^)B~&TP_$Xt(apx4V9C+U9Ao?vA&!ZGvkdASF%QrX`_(3s__tPj|HZrK|7-jIGx0?800bEj1I!3_Zj|_k(2$`$zae9j{6GvL zhu5!Ih!3re^agV>g*@P>q%sa^2YoH(DnckcT3BvQ@qPw&`;3}MajW=@sFS&}+q zW#o&{t4}AVh-pq$yLzD^BB)@u4*n1@v-G&zC8vOso1rrDdXCEE!j2tfZ|0h1_=lU& zQBp@k1H|CH>Bj8lPv()WBWq0w!7{f#f7Y%T3s5?dSi!hZ# zY^kraYG(WC2gpCl?(e@c2D-m8E#?z?h=S!F9cHt1x>c5QmDRhW8k7{eF6euJ2zqu9Z6i8WS4h>F8=v2J=5*e)eGbo z4Es%P&$e=Uz>%WC4GEf$?Xhi)gz{oAng4e*IzKZ((l=U3h9=mKUXj*Q)g{0iy~>dE1D0* zXXU`8v^dwiDed=0!9vO)hjYKl!msxMXzD4c?h+`4L z9KnRNIpf!d>EP45_P7rH0HZHPppK5$k>^@#_Q&(%oz1sf`uJmhX+dpK@;1yDgn1(t zo03CsZ-2`q9mC_aIhl?32*RY1OGjc~0F(q4PYjkQwFjS1LHat!{KOkdw1;Qs?mwPP zzQkOq$=v>Hu+Mo@XRU3qOVmoYR_W;gZ>9zcn$K~Tsm5~|0KpkH9VDBY@z;aMP8guA zp%UA&&EQyg9QB5S#)#kZvh>EBF0Lhv5UP)Hvlmk6LE2FjQQbQ*eO*<@n{}0T;;>;v zeq5Vz(dwp`2vwLrpD2wX=w>{fn%r30FpLnZzm8uQGwXB8wagr*sbt=3YAN9847PrP zp~<(4Q1XMe?+$Fi8RsJK`6sf*KFRoSOWcY82Tw6AV zduN~RRo#L@!ntf(fsfkYYs*o*O7wEfkgYHf-|HM^g`*B*kEFhc+en_~CNwVW&9x_Qb zpqEKnxG9zfx<~%FeC|#61R+pS38+yg;Lm%Nv}E&7g`|A$Q!!{s3$x_2-%s z8RNYB5qO)(gRt(dup_lTW7R2WV$Q72tUMID?Yg-7nz|x?7EzHxqM04Xg$$1gXh`%2 zMcx*+RI*UekI+a9#QT0j9MtecKIbSA{#o>id!6ldml;I5;w5XdHO(YD)w51jvpx=0 zu)YlC?yyHL-dXSt?;Z7}~`KT&njIH9(V^Z_n(nRM2=gBNt7>E#9P zHvW_1I3;k>R`AK%VeQ_v=D@w*73b!A$0vqMp8OL~pH=!5085r7(H*r-XAUU~<(c0~e0OOiYTTf%Ys}Mf7jkP^_ z!>JFwXBl2>Oa3@Y!2uP0{!Mi?lkqM;T6%ytx^;8Q=ODo8M6Q(*x4j+kTD4Bj$7C=B zXY3Uf4X<*bgzwxx2(#AQ>^5u?s%AmyrW9S+Q=={wO@T5S4?-3+2hu3yKVq9jk0KnN z>rG+HYz!N?MDz#mqdW0N9k=tvS98Z z7-1UQ%~1qAau7EX`RlkpFobu3QSak{dvxON7Lr`oC3zo)*|5$MX1<9sC}Ocq*}1h< z)V|7G-Zh2wH1@#J!IvjM(o&e>Oj+{pXS?!v!$-i~y13{B1yes;6^O~ZIeMCVZ1mk| zo5sNxk(2nt-)9t*74iws^P~Npu*Im!$Mcm)FO^~ z>KD=raIHndE5Czm6ZIZUO6_W}srI?iWXrtRNQvo73Fd+o!B{pFQy{08Lq9~O#q^`> z_`nZZU<*<&eGAgg6h*3&p$1I}ImWLGBfH3z81=%yJ%!=lA-|M1N^D)yinAkB%u)&y z%RSBA#maiS4vqcEZl~R*(C?_%c0@1G-r~p2kTi60Y^pA{5A+|35i4*aSyAr_c--OT zp>e6~aV#G}te5C3!a=JBKimL}_E<}b!-XTmQlJ3B zq5fU*_+P4+e{Si&ikZKw$4YewZJZ;tPakS1JBB_?IxAy{A;DiJTqJg|&Q>Vr!)WXR zpkWszJpDjs{Sq9RHRh^nvyKHas})TrAzZVGtj-{V1rl?KO%iSCQ3W1XiI+uto$Ygk zzKGk|K5qeC_nWW3-@V-b{8owvS|(&o_>S;Qi~2PREVlb4g%=Z3frXTz!opX5UEWBO z2(g2xlq3;kQ96em2}|)MUO@z7dAA$}FIMb;e^x%vbhNk>;SNuM2pmd1k7|ibMdu{M9B<^O@-}xiDaj8@|A*Sc zwiPL~f;nWULJE{&0%cfVRlT3yk!f=(nBo>lx^MyUH?GPmj=Pc}-0ESH7)cT(z4pF| zSlV1rRdMvvS->JRWkuLrV0m34X=LOP8R+z6e?LUhCs6qQ~p7inAl&fI(L`!pdintu;v0!#Dvu zX+#p@)FQDUFI#(qu?S%)J0f_Nn5n}7gB3`zNv)6&{+a-$}p7j_vZ4WSQK*UMhKh0+xxJ=8)($C98 zrZvbz7L)wq4qG<|@SLYA3Pr+RExstlxm_tjS$C*)d(fVvsB>QYt|H`dR=y1XF#u`! z8-^|pQLvp~Ms&Vu?z^SMII^>|{(zrQg&fTCkT8)xub->~lF#c=HjR6s^*< zCBNrS1wxt`^OdF$gHv>RYJ{c2fRvv8q~&VO)fe{*BUVjt8dI3$kX+Db$iuV~h({F4 z0H(8iaxNtvO;pYXEqM4MWx+N#;vcspys5|YtScQ!5aU5%z(PqxKr_?+;DEF&Gl#@| zFsWbuaND0+GJ7D4ESS7Fz#PYN!gonNhX>eMwVQjM54ddJG$^NKO#^1GD+)!=pp%QZvxg@w<6-j~HX4&tz z_48ey;J-v#b_$X>-lpi$x>m*5B-`Pg%$mh|4;aV)(!t7w%t>pLW6*YG+n}!lSF?;L%QLj~)Z97fv8$-eX`g*vmPCMDPbg=k zZpc20W1l(*pt%QvBIpmM2s!X(T&%NlDfCC9==G0yCI$}nH2X%KIDNalvw0U2fWj_u z&lh`+vm;qg*WAs)=+Q*E{DL5bIRwfw1{xoIAsbBo>$=qRK`mz$lSu6I^oFGnY8Qg?kjyj>ok*~Zjz|TUaiR9qS%U75E1rGEY`43V zm`=5^VRT_b6$a$Cvdb~VeHZrYs)L!fRobspx{eAodCjKNt=Dw98fSMhS?I`NGqE50 z6ge>b%}(@28$vLdrAsn1{IjDG9NhF=USNV|BIQ-ITxQr9B80YLQcDjj6J}J6EtRdX%Zeu?sCxL=F0ddXUUe8o0@CPmIt1`%c+ii>pbRJ z-RZst<@`r}ea=l9N3O{Vvd5A{SS&4NlSFx4KmDf@@*A}ni_~Ew9xcrfox;H0zHm}x@9?d}PzTUAhxZoN zwUGY0gwipRH*ge_yk0BaR_ZhDCJ9^8c-r`DkGEWDYO@{~XJ{zh6QuHfi{z4|e(c&L zWQ&)AvdF=pME>DB&{P%t7-H0WWmGBASu?p}n1)blI&Ct`cLh=b8hX}@h$C-4V?=ut zu6h|MW58blso81^mw;*5?5 z96#GD^al_;uwIS^epZ3ow{&yu9zKiIt%;v@57~Loq*%Ay9|jSF2Mwx$#V4N_=8IBS z8Qd?rN7a0A0#iMk5-sjUw(uDS9JbJC^eM^eU%VoSqS*E1f0$r4r9F;W{ z5?ZS9pQvT;(fT@9lo?!6n%FPyw{ksvQKCLK>`hN+Lw3Hu4RA4DafWL9_B^u5+x=`a!{JIujd6yba7J>vm+4OBH8lkW5*TLMMPGif==Cwkz@~rD4sg zGpjHf#_csEURZ2Z5m6-ZqRoTcF2UBS^_F)&ox-NXRbwY#eJ*{fyrEQj7j0(~cy@nL zqJx&(mn|bFa}a7>K#yy7dn-DT)t_w*;`j~pa(Az>*p4nc-a|-EKi}*80&A#Zgv;Yp zCW(h!8l>hlUEVOQ9TY>Kik1WdAOwjaH0XS10D-(5sx^YuY=m)1NG=`x*x7`%yZ`5C zyu(mT^3J-_Gg)*hO(4VPqX=VqpC}7>s}E@{a&02u+o&n~X`k#9M(V3|k@N_ss9!B(zd*&>_m1t+`3U-D;bZ zUJrrjr^ln*;vGWr^5hgVkI*@RQGed}=A}Fr<%%Y}^P-9;C~ryoB8Q|$@5A%=jKzwK z_rOr|-a*G@)+*!O?~!EJGv=^Kx*+Ctq+(6RV}~;$PlYsEb!u6C)nBx~Ge(3h;EbB# zdfbER?EWGAG=n~0ShYIPu|#Ttgo7KM{=+$Q;_8ZKqqCN5X7&MWZpQet9%i^7c>j1= zogw+O*)PA@kictGmDAYx!HP*fnb z7{5d7rCJQvta#)52h=Dmb48&3r3d-;1>*i6AiV#=qWHT;FO2Q60A@f8BG=SugvR#@ zc$i(+Sqra|M+~6#uyMu`WG0J~d9mer`o^2!$Qp7yVFBOg36=Vpo!WQfg7EE%UNUDu z-!OAu%cN$LqR#>PUYm-U*Owf8uki^<8;1C~Oxx%HtASK8ql00tO?@7C$8UrJd zMa4F%?7DU1lG$CsV%!e_UJ3kNTY?x{|JutXcjeD$Tc5j`Ok{0vHA(>i2^*J0Kdb#! zLhPrV7Vq`DX|(@3xSBx`^MtWyZBVml$=EM&gbDK*RnBQrS!_Su{f|_L1fC(Qr@sd9 zpe1|}Aiv^t`cEkQzn}Gt{GR~|V*^J6y8k(_B>(OA1?^1?jE(G_tPM?!{|>KAlz?R~ zKWf0yK-w~Dk02e9>!Q>nL<0V4F1dpI@jIzoKx8_c73;3eSr5T>bR2;D=avCJlP8En z>qi!l=Ps#$a0*+Ma%0mheuD~_hbk4h_I_146D2Y?5*ZqS23Awys%heW7Cr3%AA9eb zVXL>i$5jIjALN{lS!dOOSTiTn9~0}nm9xR7fR##HMNfosjk-$Px%q`IJ8+!@ssIY9jPbA-rm2vfVB6P#lTb$8oz0kFl7jv4xkvtDgWum zo?v>;7#+Sjc`eUKE1ZYD_njSu!zwd7VnTomQi>=2>hCp36}nMpY&Vl7v2o%{Sc(vN zsKGX782$__z^PVqNR=7jCN08C6E9$jEq&`Gv;^c*3(-;2ZJ7O(Rn804GD~K z)ay^*wk%e}|8WLhsPiJk2<~IJs6le2@-Z;!Gh(6}f7m{!U{NtUBHk7l%7aVqICjd! zJUH71VT31iUD7xXP%@}&IPT5II|!aBq(Ne(+zkM8xPf{Q5CG$Sb{Al+mEm1309~fE zZI*AWQQPKS4PbE`CP0^l5DVZnaT5`G`-@p+RpU`6{I#Yj{;ea@fAQ%3YhC}xJM;H_ ziBz`yYs6G@0zeBroPrk-4XJ=;IE-#yRT*%tITd>f2?$VL-Xgsx*>G3i9UGH1gt`jnnqj|{bv1ml@74hddT=*KxUS)}R z@hIY0deg}SqhleHB~*XxbjjYRbCA=3isIS?&%Z^G2QfQs-5$%7^B4Y1ZO5~Ma)7gS@kLJloCIvH6pN|) z5L^U(L0I6zA5k|i6TAG5H&eUN9n)GO98sCkG}4GPD(gNZ0%}R4gx^--b?eB^QG~S? zi&mE`cx5h~JVXQ`0QVvjRGFo*W;%zYP1wDYcx%3sk&2n`pc8Uvp^l|1%c!!cHkuzl zhoPGnTa3!Ka+yvSWKJK&J@A+tNOu-YoC3Kz2)TC_gnWAi%=7C%_LfMB}$+rB+j?+?ACo%&uaBp?^19-p2Mqn06o z^&HwQpj;X#4pbf52NW_v%Lp|P0Rs%pJSVttDa|csP1~+M?hi)g?$gGd`fI&6l!4_2 zz7Gxg*vuWqEza%~ctVH~=Bt&E*3K9k432@Z3)O({jb|1+{I4R;p!w6omxGuq&BIEH zk0d-wD?Byl{j?3|`?T&ZZ`*b+Q3~vk2}M^s-%+uQfwmM&Q*26&k)&fXLt?aAk4K5o z;!$%LW#;CJM=$dco)#JX@mB?c>Kz9*06=^Qo)?h3A*F~}#XlFaU7ZaHl0SlfBlhE> zVg~zidGBWVb4JLEyF5TN%#|I(n;!#yLS0^f;uiNB5k3`F!yi9~=HByYzeb&L@qQAD z`2BM6TJ>m=o1$dlO@GM+cREBuWW@sm(vPq>7dtiU8_IQNuF#K-O15 zY}s050^>4O=b%#M3eX8FD_no1tq%2jA2EPz))C;Y$m#JXi^IlB&Kn6`t|}ZJt_ek@ zW#~_+uOtD(Qk@<6j6Y%;K6TG~(_a`dNQ`(6{PEPVh@H0?p z7I&?}(D|`eB=1!G5+${XDk&})RnUGOsn!qN_p_~C?eHhp5ibKtQ)W{|h+5JEtNUV4 zoT&V4&`$}49m!-5&vI+3a!Sc0%b76U<)-|WI^6V*$jmtQo*3!7r)juON8E!SBU&G$ z>zJ4Hu&40}R~Z>3{sL3{jA5@(U-&dgv~-1jqQRjs{|m2QBdDX}x3M8;Scu~0zPiUu zp4eNIuT8XyNSoNRV%hxX$mNdP_DD*~3bL7~GRc1bB;fvQ;5;oZ0iEjSS&YjMLv$-G z@o2>s@I}l+4^4j{i-VJJrBXz1#-vgcp?M_2Q@K;uv_i+vSxhiIYw4Nf^1G(eY9#FV z6$1U05h2W#QXyDe*Xfh*c#uXx-qp{g%(@UAsYRxn((%FcQn#)ly_~{JAf=l*pp^~M z`LZl^Vwk{PnF`0ZsGh9E@|ZtT_W~@iDS=QFfmp_K$#t#9KjIofTM^mOiW_#acRI;ntyi4Onny=@OnR`bz=zf zP_Dxqq1mIwSE3fE<$kx}?t3EmN7ecp`lNgE>%bBQ|95+Y@V_l5giWjr-2P>ADCsE8 z@uTu+trpSv3W6orC{MFe)IM4FKp5aMDa|7VL3ph;QNb0gq!o-`XM4tAVVV6^PT*dV zu0xhVhIdIu9FS(mk+_6#TI}!4Lvy zId`71Z}6^>@;1jMQ-f_rb@I2#Xt2|su8$<%g>4oiRE!5+*}9MyycW8l&HBg7(6TYc_=3zK=sb1+~M8J%y`KB5+=e9tdiaUE($l z6kVTXZNL|}Al2;HZe7LhDf!(0t}vISyq{1a5a9*$`d;#m zl6v5dMX=o6IO0HQ{RzW|sMir8r3Y^vE)b$!bbMKS^a;K)J5o6#NVJpO?fAz&Nf==n zsQ;n?$u2;&Qybn076CH3ho>T@TPf^-;sKWKcs~Abz5f5=>@9%eUY9)3;1b*=xDyEO zkl^m_Fu1!*1R30AaCZ&v?i$=laCesgZ<3tdySw+?^XfgSrivP>@lK7Q-AV+x%)jL_QS;Z(W>*ffb;J6r^|+0!cOP1 zLUbWj5m|{h2*63b_JJ{+hQl2=r3Cp1vMO*MXc$Ku+jdu$B+n-+H-_i!DRVh6TdodV zuC=M@7qDx`sds3kNzZxGV$I_(Wz>yo;6p0Q+oRxR4NWa`MKG7*lacRtF>ws>%UHR1 zGg84;wl$1fgnO}V+yYUa)l2OnyTKa5(YU-2&C$jD;j^ZaW1)-eCVjfL&;CW?$X73x z%YZQV1U;o|#QP|ubKTV7%;vB4IW?izlnw0lU7e^@1dbnJ!NPI= zIQM-2=TRZSRZ*GOWC6iLZ1?P0H~^5vW}#`E#6uztLjPPPn~ReTjGQo>ESq{)x)V7E zUBu%U@m;sDP)>9oVGysQGkg)sqJISfc<;-0=<(`j8{K??rjC2d{;{9+Zc{xRJKm-2D zw%&*SB5sxouc)olO@zKFEbmZA-}S=h-!%|xXkvUJ_~sw|$hj-m6FRph*{A#`l=W}Lg<1$My!aGU0RTlvZD8JZbLB4QyZD3lvY z&CVt|cgL%+w=zhLlQ=KBWM)A;i!?@T4&S>W!w8=vCL}5LRu#BekRZ3kA%f+c5;N$K zN@K=gw;(oEe$cE9Q*wk>0-hX{1n6u-3lPYh zz$8^Ojtxfk+Dpj?h34*2wv~|{13n1+P^>s0XF|dsade^EQ+I?EK%%kQV-2XydGihA zvMTjj%mJ|wJ5A}FcAQm|XqQT78uK-b4jZz(7xE6GNEs_L6Y}|%&^5Z$k=kU?M<8_! z(*hwrGRDA)J{L&-i&Ziz^b?5w!lX;f})I(*CGw4@to zn#N0dpyQXs%v~5@SXBzF8b2G7Sn=~7dZ!{9h_(g>u$u2jzbO3fPzxJ0GLph^L@JK2 zJzWsmM(+*!d= zYINeRiFjaiP@eRDqw>`aJtX3u-={i|HN{CyAM`Axi<}sWi!3bBUKzjHzDasSrw6SK zk4gZeFbHWjDN+q&K9%6&W1OZ+6# zU{hQix9@wN<&JbmWB@D z;SItR%$+>5Y?Je=56W|42!>?s8e7rqv2s9(Qy{mA|)oeMiU#U|UpI#_^iYl7YH zO5obO3kyOTu7>jkYC1T2 zU1A~Jz~!JwM9{e&$Z-^q@#Y=3dKoGcFM5Zl3YVL4(wPxFYINp+J2SiuSyfX@z1bA3 z>v@L%S%v@C-OlX-$!6UI?@7?I3Y>dP9;nnQ^J+Vz*uO<|YOG|X(5I=*)xm&lU+v0! z1@Hh$92UIVXXLLT!E^pxQn~@5H_Dhoc-<3zX9%=1vfGT*=mVu8LNA#BY>jQ;;yOPr zIKY&R`NN#0E#i_^KQexKAlyBPlNT<1<*G)qr{aEAs`MKgx z!`OAD{casBozehLFZ<7B!oTS(em^Y13rGJ|Ak?Yb{(4$|v?EC@j5K^dbtS@5r1*#ZbSKCq~u|F*h<%LGYC1pbp^i>bCVG zsF$*R^{k3hcho(qb=1K8L8FR<2#Ju&m$6>pfPoLwLodH>Yeb3QSz)(@dstzYoYECt zt#0oH%r3`EBU{E}`O(sCQH)J(nXc|Ajwe&Tpj)bLQ&~S1!XS>lr5X-M0~mtLU$fIq zoAggKNhyVWxN4LTS1^%q4_Zsqyv;{U=MHN1b5~0nfB`2L>y?>=4w>+_1pWJd zc9C0(RXuxAS+PZ0q8X5%XXnZ zm0j7mWj5dr_lnY4K=a6#B6^Qu=GqQg?0TkfKyy>9p{BUsckU~U9Q`E{VwJaMCWeI4#t-z5(^qBW9nN-X*(N2D?1;;Am^Uty|L@QhRIBs zx6617>&(!B&(jt(?!3%`I117ELfZH_T=P;x*3!+<2%e_G`pMB6)LRKLUqVKb4U3{p zxY~Stft~~~tQn8k2j9pd0(AMQ#){ho4I`I0Pb5C0a`}G~^?N*Xg^vte`<|K7*(7;( zF6r=z?M|1{1MNq2{3`=^3mOFeGYpZjQ6~1aI0*eX*0;6dr-gzFxsMcM((fdqi=bQ7 zq=Gl4*T%5O#HKKEM8#8HJH?)piheo;?s&E}g2^Cp7Hp?SsTgUpwYR0Ypn*WNk&)pl9Pti@KCXsFi z*?T%RaX2le*yGBp*ppF*$cZ)C+ct)tA~~9$1iP~GwKYq)Oi*6|#fn2iy+dM)h?F3^ zD+ar*8M6D91A(eYaGcAA(sZv~lTBfRKB87p^^Bh}w)fmhzWlanP=4zts{@zHv?%|S z0sfwA0%rhaQ!`U1Q#)hRKX75W+OjgH5Sl=bEfoVAx>9tQ2Xa;!ZtJ@oG?+56@YcewmY!~WYf+gw^VltPdJl3F`tY^!Vnz7J^`=_DOD?GPTo1Qhn{ zMd7dr^;#CB(xNpiU%CxB176RHrc3c{_1=`=fGcQ!H8frsYb4*|s!`Y<8}d?*Uuxc1 z8AuT~BBTkm1O`N)EFcLCG%(jbo@kndPmxFwJ2_7lkIh4?Jhkf5?X-=SSn>4g>**i~*| z-ur%YIqBQ{0d|1{grp=)lj4ZyQu3x5;qQcfw5o5W_2-UwVv3jPn3wHRUiCOnc|(FfztQCz6P-Iq?YSmI#U&MtxLiaOxw9irDC(ZIes}pLxY9I!i6PK#tiCMLN6SG0 zQFj%kuY*xtnKP1zuRUc)DEhk2Qp;OO8a*G1c!0eAEOPy!c(~>)Bfz>f;hm@{TN|Ss zUeG;91M{ULv_+l-98$yJa=GgfgfYHlZFq{f;nY4>D6UFeoqkkD&bD1CHPbQ*i;fxc=3X z2CC{gPphK|a8)yE(S{rb2tsDlW%r?AaoFyGrqMRJ*VY#Bu|^yD>2CUh2Q~1efXVN# zzt#Hgi-2{)mW4za_ew-J`Ymgm6^HoVZRYOZGTKT@=RZB&(0sOckQjjOX(ByZ&{H_u zo4|Bij?nX_;dU_MIuWyErevUuF`78VefyZO#0cy=NQ(6h-;JwRrY)o|4mgoqY$sWrkM$G=T{C z8nqvh#S!O{cZY#t?TtwFHk==(!aD=sqxX)sKd^~fKAt5t7!B+7!VsP6Xm-Ox#t!!LvuUsg~$UM{V5fHj^Mmo7fEqm#nf-@Vg~VPX$^59 zQOc#bFA6SwHZ@!lREH$dX@u1w{)~ai!mxd@8TA?PY^Ttx58`Sa+#uyv+pV2_lhPxc~z;|#D@>AZArCLUQyjyeYui6mgIaF zo}T z#l0+~((o7z#x#3)tS$T>v1)HuqMeM0rG?HZqGXrOdHpOz=x3eoVafDs2gG#bBnBIh z;$|9M8xM(*dGlK>WCT?Ey+%lEW}oLz<_99b3Z=->>;*EmA4?4vH&j{2nmZ?Oc1X^1 z)bTK#l6huEyN8yA`w*7%2nt3Pj%=@JM#NZ`i z8{J0c2-yxQb_vX)t5&N{iLZ6q{`p$hhZ86@K%MPda0MOx^P>?EYtm>!{b}{?pV@=81ot< zX}0=To1YMKGm^E_ve9OR$$8@PY+}A?1s}u1ot?N~?TXK-l=w-TpZLyAK1}JaT{v3| z4^hSEzNN`jjVw+}hkW-~@Eu=>`tsjQ=03fvlyirOUrsr3e+BU#!7%eXX1hBqO%sNl})qqS3is z7o6k2u?BbllQsDEU#x+A`v{Ns&Cdtl3(QVfPA5r2NfBiUL`z`ze~|`l7Lt`i(fSQw z(qNofmHzZE(tz0ohz}+WZ2yo3a>NcbW(~)kP9LOz@wqohqsp~PM4o*^UO8h@Q>$;4 z5si668@r1XF=IxX1;{}xs2g>9?KQcu{3j2It+gg0{z20c(jsOQ0e_0i?S z<}a%_jwn^cdXW#sFg=s^tTwlb#PDp8?K^hU=+DY>!~S-KUgwnWFx=Z+zyK;2e+#DM zDZksP_!*yVU?P0cIQ&iE%sn28AH#$JO!1Q+UXMg znmk=~pU!D0WGg$7?AF~Z_*Z0l!!f1se`F&|Q(%uwJe|rAHzDzaC{ZD2y~k|z?GVuB^mLA3UslRcpdyUFF$>dXGj1er-T29oWA{AW=zi21z==j`tRx^ zzH9sW_pq?AIoR%XEu&T`Jdu@V?}*`OvU!*rKuL?%=E@@yXklM4C0SV< zAb#tMj9!OqW`Ga%1N{2W7zoAR9$Vhj!{sm2$$v>${s&Pa1A~Qy25lQwO@61fB@`Z0 zkOk50|6XnxL2uz?W|eXBB`<^$1C#hC#53(?`YPj$;%n67Q7}-v!gf2p`s0)QCkT&_ zI(G74tKj`$imqsZHHnq4jcxWeVJR*LNFi#|oNXLHi}tS|;a_tYh@d9$sq<^>+2wQ^ zg9>bCng${m&li_*GMBoq@nTyKq)U$xVAa)E$cXU8WO=(cGCV1rOpG-pQ08g(hKRng z9Qy*deex?^iWPa>38JN?tyBl_D&kcATOwSw3VUln(zdiajgbf|d7H}dI`4XhOw0m(|EsVS=w9L^uim$*6#h;}Tpgg`Wqpa-D z88{z(eY>(Qw~i1bNpVlyceY&D#hh|#8z;5B)%`Y8-AwXyuwDhzUe@&8vME4GsYp6~ zImVaj7fE6d)4xKAgAe5MWpaH;15E63B}uI*5sYX~o@owX^5=_Wwm2-+n{$foQLCCr zs_{wTMYf=tEJ<7_;z67-HXJ58?9wX}*X!hmaWqM;JWXL#2I@GECeozabvF0uH3an! zJTJa9fy_B(xomW}+w&YaS`CvrrtsOzSY@w+l$juz6D``wUE(O%<=E3}M~VTt91zW* zMlpNpeM?LwFG$wDOvAo?OpCr`OeEsRnPM~)NV(}3TWtjCL!`CSc=k(oY5q{HKQsw} z*|1j-m?psh(f~K*Z2rCX`>o#k#SzX= zRcn^#_8g6V>Ca?QE~#n5)eG2o_jJTtw^TQ*;F`9#}H0b8cnO zn>#>gL2XjMBOi!<9lK|_Tvgw)q#nzMBsIBzKmjZkuJU>ikdif=>WmMu)P3H4!*RS+ z-Dmj5sgS1r77yq3>>kTVpH;llxKdz6Qc|B9a394!EHoCm;>VI#rdh_0vNw8FG>_=0 zUJVchXzWk(R1l9F7vX=%X1f$Kr{>bh%?x|7;0I0w4hen7#+^!ibNwHp*H zZc86G$(YUMTUwzM@=e~KUaFIzoGs7VO~z@}*|H`fyT1%Y>7wb&%xet7$%6(F%s{e0 z3XQci?nk;97 z?sqKM`={ge{HnI-)Dv93>0Gr=#ZT{1mWUu9`Pw(C_u->L%a_{h?yscA$xq(6_MzRi zT&A+e7dZ?RFD~7FTZvX~#18V#I78w$*1W4!MMmTK^gg~h7qwsR0jgI}PS}0?<@JO{ zY?dd+yk)D zu87+1WB`x~ z!VxSVz8LHBb|Il*r{bd#zV6#-#LPNTCdgW1St(p57kbG++*D9e@1A z5yt-G<)`}FN4_$^#q|GHbgF+)50Q6--Tk_awDjbNDFHH~FifwDKF1e_T0r#qU$9Dv zS4SW9uOd^uZ27B7Y4!P&tVw9y9KphyA$TUGFD5%TKVDs3Wp>bXKrk3Fh7v<#L8}Fz znModj_3RS0k1hc}J0- zLju)XBpvh|UZYuyMMtdcNW_Il9@(_7*<3Zk47vg6DQ24@?pmH(R8*zX+pTlrmpZgm z8zsW@c;NP5#Cl8g(Vi%~(LuCYv5gvx*@SF}I4Z=yVZ00h3`8xYEJs=%B~^`b>SfU| z=#!3m<*H-N;V`LN(x@@Zv^I}1>OFID`OAyZuo!DtWh;9#rG;ue4>IawMt%+EjJ_GF z)$#BIcGY%#G#l1jill|Fp5tLt1+^z#Ug-iYurXHI3Du>__U+W)4W`8aCaE&p^Lwi; zdFzeOn`ypB8b-Qp6Hcy_%&$mCveB{|vB#b>>x*Xtgt~GTYHlFdI+~jno#XWGeXzW)U@uotAH^ z&YNm(U)vuZ9n7=>;72&*y;81DpQNYai{?`? z$ku}3zzs(~AbvWYc$4Qz`uLiG&l8D?&ox}r?E!CyV(GNY_W>9}VH-Kkb-2#*1@3c8 z?8l^**bJ|gge&Y$5$yp;=vPEvIKNPGl(Ki_UuvaLDGg;9qTQ_@eyb^Gf1)ZDF!kB% z>AbDj%cbnhWkS=2B^;8^Fx+B&jt=69BkZCq057UbveO>sfI=|+B)p$TKEp232FLb( zOVfSpBk1Y_&muBUu*5qnoTycAME26&QuIpUj0s7!LzpUZk5Etk9_QAARodhBF2wIf ze`Hlu;{18+tf8jG=1GPe^lD?C=70 zGGC7rPEg_5MHR%=y=Zm^LeqzNB*+1UUq+m*E@iX~Nbd>t+~iZ+$eB9}#}4eqvSHfH zdq!W?hQ6U#RKUgPKUAOO|M7E^1UOrm{sj+3sQx9^{H32p#8yNT!phT&#y-Yzv1B=K#byU!j}GgWRg%J()H(;1x+g&O(QVo>(0#AbE#h(I zd-f{z?LoJ(otyH9rW=G%c)Cd+gPOdiJAvWvt)6PdPl^Hc z8w11TTk@7OjG6c5Gi3mDVWwqx9#$Lp8Emq83nlf3d~)cE64I0^JecO(?Ydt!iHAf0 zL7j3Za|GR~bTXa`c73&A1K49Z)px|olC(soS<_B&e{cQpe$dH@#>xIYS&B}@TUAmz zeyB=3GkaBk2yz9tAZ1ixaLGA?;ZldmuFGCqJ95~R%K;;<@QzGOv2Q z@Y^W_MaQo8tFyfR$9zlrA20d8z>_*P9hEm~XwN7|C!MU&y6*r8WHQ~R_>yxny|fU> zv;bEK7)t5dVSqa%CJ^81T~hpZ$61$ortbuOL+!;H>e-Ni$)c~Brs1vRg^}&C%Qv2< z>#O;~mTv|xt#_E6knQ6+$j1cAyi05G&%3K=5^Y`oRF9O!KwFfQ72vcnC_v{j5om&Tnf2}$@ldZyd5O-b$E$jgm1{m zAznYngR+IdYl`o*0u~jg04m? z<$YG7;z?#9ql1j4b4*Jbm+Acq_TKk~?wVZ8L3?pK3lc3>_5rW8W_=4F=PY9sve`|U z2`7%sVa%q3*Pyk#!{qem9BA%CqHOmi?L|hWi_*E!vHRoqV;e+3rMK@q_3;AQJzLEJ z;q)2zItwAYif7&Vp>Yd(XKcQ}>6KAo+6hH34Kj96L50lr$A^?#IDDN-!v5*RNxX1; zD}ZlfRuyQAoata$iIIA&Ae_xnN;ix=|8?_bC{-BL$l_i)17qeK$JPkw|=K^{jQ7gJTUuwI1W<*YCLUTNpX} z@#I!HAKD_^C#2@l^z7J)oP9*3q;TWnT~;Nf=7Zv0$RwpU^`r^*D3?8a;%0={NKU6N z1-u?p=lDE#2s%XY*jz38ZHQL;k9oZ!d`coeQe;*b4-T3i;IY8g@*?&NN)T;!NM~MN zu}9~dlPK@e7(g`&qhBk@dLk)Ndde!Auwg9|;&u5}|D=B=*SiY)JkxBVTE^1ASL!z+O&dttZFSkqastmM=g6=q>tKaT)KLeqUL#r@iYi)WXYiZz!i+I+eyd87 zXEt<}ygB9(bzd$3=N3D;bEeWYBo{qnnOP~0;)_W+A!et91MGf?!OpJHlGHh+_- z>%p!HQa{{iH=#MNc|TOca7wWVQq%`_TN;<_)#4f*jF&jnSV`GGJ~VSTkWMo@e=VE$ zO-mY^`S|mb`%kz|di5Gf!%o4eUQ%Tw3h$qvml;n^mNG^4N?=8-`W%T~IC=!DYU6|m z@S(IYMVRpm@|NnBBj2|A4%88@?B3uUzb{Q3h@KGw3SY}Qk7z`;=uFc0P+w@1YwZ## zWtoV}VL3#Q9gm>(pMBMATgg&Bz@FpXq^5RAcS%{Xt{4FtCLLGSWLw5j7dXTXWB+K@ zEi^ch;oW`8uBSQpn12-r$X-ZQvCpd&F%3%IE~R{FU#>u?8?$E2j*^-4v<`YJ@j;?1 z?}rO*{{BaNrAtn5@fQ)LdtQGQNZzl>vJ>y8ZpR#syIE>@VKkqkfwaiDsOEY;H_5Xt zp9bQHMLF5(4lk41_io=vXC`5afJ4GhcM{{``(`-71X9RO>!aZ3JnQXM;m;LMPcErA zb}n6wB0*&jSbf$}gJM`H(Tsi6eBuDZc*{-4J=p+Lv?o%+}}dz&e+J6@XxR$QtP&!_yCx?Aq@Te(8y3UGiZx4xpQ4 z=s?$C>J;5mbV0rZ%UQ)9-hTKqwmC9YHu4~)l+7kQuxfl0tQsGcxWX1byp+@l8)$UI z|3u!KhLhCq%K+UkQV8BaL+(Gvg!fc}7j9zFZ#>jg8XZRqTZF-&9TXGXjDO?A5tM+MNJh#~VUVf9^$=52c>ZlvCEQ^@jtA%I{eR5Ue=i491w)~(PJihDz?G=V5}4zd zdnJSfb3Ub9dXvMrMzz!;X4@uPI6g5_)FZMCf^j27M3D2FelC1Jlgyib{?`aCDN*pg zn&>05OTF<$XSbK10#C?>$jdB9f=cL9XyO56o}E#R`nzUoKd?I>;;IsDc%*fNwcl0O$B6R zRIo(3R!&ker9A}7PHL8m*H~iQB><#NB&GR_CM57Ef_&@u-ixxsD-+TEaBvG(PWli&U2urI&3Fv#gbe6mgw7-S@m+sLV?DLKM4ygn^rg& z;)DrK72oehdu^4`#ijlloHv&GQCJ=;3QxQ>aioEdUO_M3P;ozGI!;#fj30>Isu(l> zHIxIm?@Y6dN;^n3kq^t5uEp}k-7W|~tQ91D`^COd3p{PSz)&lw-0TzsuJ_4au8J|O z+Lm2!`BCWdIxU^T#2y&wysh6HMI{rfJ#`s}n4W&Zw84 zSl_${c~fKWg($hV!a>%YTf08zhHM$ zrlPkgI*Q32>%Mg4t%STQ70n}=1oLk8PSsj|4PKTj0jPDDPUuIPYsAhmdo<+?+f>K~ z8Sy4UhEck@aqR;J;eznPZ+B6@Hiz0ZID*Fhkth6nGU2ZX`d6|0D~f(Ig^Y4^#kJcx zv|M06EGTrX?z2-&Hrq8T&SO@)%`!G5S+Ugc-lq#8Gn2ISUmk8J{#2|Y&iMC~Ej;(_ z&i6M*_fNZ5xSz3Y#Lxv5!E$okZlrVHkG(a#Ty8b?VtutGNb9C!6KQHdLwdafap+aV z9D1)T*6^e`yBkHe0N*V9MS6D+HwhodgTz6?Oj%$wJBuu~wj))=d|!$Zqg4wmC_L@T zS5Ay+Lv&^HhPbB)wMw$Z_TjA!C`J`53Lmbp+ehjFp?%kCPM1+0@~5xZgca#!35(3f zZ$S#9BT-htZ*o}|#*W%*ZZ6)y0S+aMy7rVI0z=;FZBsd`_TlwQX`eTZyQTv6>Gf4$ zD@Pu4Hnyft@rOUwsson87UZj3LL$50mNy7SYh3qKe|7WFqLHaKRBzPZNTlu{?2oP~ zR1z}Qm=Q_8QRenGyGCxf%XSD5%X^NGnzH+`jSs8*OaRtpPhEt8O;4^lC_Rl#)l%eE zy)tAK@<@|8S`G9@GI8X+snY47;z^}Uy~4ZZ-|$ij&1a%6C}7eRC@vyC_x*{f;$FyP z+#d3#B^D3ETTP{^P;<%?u{!lthgy-zqUQCO>=qxKfb~W#?lEpwRM9yoJLlYz*WT5J zDR9@?6>5*_8{_j}i@samlvSi92Nb7^-SYeQ?`xx;zisn=;N!5z>vqyZ)al}lh>o;U z{3>NWODt`^{-sKAlR|KwB{=Vmd9BRw{$>TciiKLI#k=p+Gtj=ic^snFpLS?8&32%r z&2FHpMpqCp224=bP}+KWW8Ty3r=OoCb?bGm4snmJ4oO0|(-_0B$USOCzsfQorHIbb zN+54UY8Nb}q)%2sdiBG1)3ZH6ycK$^uol%9{%#K4HyrV7ZzLdbNSu|e5U(lx!yaIK zB*GB3#%_&xl!M=tFvP|5qoAdRm_`qB1o7x&v~haOqwdtpmMF~@+DTIp%!>Orx`jQA zN{Ln!tvnj}GMe5{Lj=@w_^9)=GNtMY02CAR74C1of(#u3{{IzU`g;}4|Mj%0{DMjF z1fXo)Ej19~$;pF<^BIQ`zpHF@5g5mLh5W9*2HbvCUtkLlxcah?eE_$P68If$ip+X% znOdBAc1L-BjNTr)pVEA$@kr~37f1drkxAkPQ*?HY4S)`8j^YEPV%q`NE0i9KcO4&K zF^yrTa9F?M?c`f6*bZQS&)!^et!R20-$Yh&`ydUQTOhhRN!;UPil&Lk^?0{|#Y4~# z-3RSoyj`Ilxoo&F3N}w`-47RUM`OUtX*C90VpusA;$)!of( zGgh~Aq`B@~&Cfz9P51ru2G(&;39kKoFG7BmSdMn3)}V)N6{Vq5%c>T`@qKA`_kie)l@8kfXh>c>DQP7i%?It8hSmxh~~ z9KXBI?dDTDvO!#^&qY6VhIFw&xd)BQN%Ek{K7^@CV|qWV4U{{BjZxV8QZdo2Yuz+X zOnLASv$_DfG57n_QOBsQ?5`qguTSQ5x^qEvs4eLmhK{fy-kE$G$!Au>`xeFHkkX7N zo-70;z|80Q&12ko`j!gCFL`H3E9RO!8n95P_&7l##XDq4p_a;rP%b?m!AU@BlXA!6 z8ga~R@AS0r^@mQx!ykY*(>BnTS90hWcztRe0AVbgukg?m1`#Ji8Yb)z)WwA$iy_cz zUWWoFqJZwJ_I@jEGRmp6Jo$EFkxc0Jw6OPKgy_C}h^9Dm-bwekAHq#;D3TjPw%68> z)XAy%SYsJ{{8<>pSYxFOIRwkea3!mY4({PS!!)T8H3wF+LXmFIUPUqA{w}YW?GyxD z!O5ZQAIq!1$4J$jO`ZN=q^6O4DBa9>{!gGOK`lHq71UR+d0rU>!h~dRyvmNqiI0`` zbl`?X>C8q$cnwATq*ZTlI)K@U!Uhcg`lf7y%QmmYsz+xX<^!K4zEgKArhAt+0PBMu z@1ln=v7a46*zCide_g{;5o5NZI^HR~+SW^75K}}`HL;)Vmi}!lvz&M8j5-=T1*NIu z$8gAf*d9t=mL#9}-`OuEJ~#>lMsd2pum7(d(ys&luhjS3ciyjDA1|Db7)qN(UW=`F z+7Q}6A6%TGS{tAY6`{(SVrXg0AwC_PyKbm{{h264H$ z3$lNe_%)>$rI!II4{d<7XMESke;LL7@aCy*H>U(2mPtnA;4M;>O$BQJG?0N(1y4K_ zka=<7rqbMPFF9Y~ICd=2ex|-^9ty}>P2>Q|7W-?>Ww;!|__L-66YwFlpEznfB0b8e z&DI`D&k_OVeYcm~EfBPziIcJ109-wid*=(A<%ws(qQ$9w(uT@knY+Ha^SNSdE?8q^ znj{U~yv{784C#!|Zp}M1G-=N_4k-?GsUlHMDW+Z5 zxz}}GEyY^O5g(_;s-MrQg@J#F=w5o}_?B~Nkwl0;RbgE3uqR&u#09kGT9+C} zbd}d0S<;s0D_FUC2F&kwA8p`xjX=-abad6Cg z3Ji?wr~DgZd)0Jn99G%;kbzAozWa7Xz~E~5N0VfYx(j{Q)~A}a7y#Z4r@M9J*{-xS z$5J`5ZB6=S4~TKH=cnaMdn9S-isP_y>YQYGbH!OG%B}CZPGg_LR!5PxX7=*Fy)+v& zdjW28mgB(J&v>k6ev>>BQPxQ}{Js*t46%MY7zpl3mLlG1SdMRUueqNDST194T%IvC zpZBQCer`~Ue}_ZiEXPNh;FY!}5P@b7Wl19)ve^U1al=3tGPm<2e+JGo%S!-kmLlF| zyu3PGwLj|;<^^5+04P3r!nnr-*wAJ*R=)!@RLE z8kIygVfg$8IW`3th%c+?$v2^be$~{OC>MS9^YkcGs2+Zz?5D)hV>pz71KwUVa?Eas zQDP|D3*3cfz?+`H&Ij^$lNqF|7``x&aIr4UA*L(+Tfd2Z9&5uBad6^1{Ktxv?r*VI zb%2fQulYGDmgaU~73#mbyFVfqm8CyCgQ5_ONek)Qk0M>7EaI^_;*um+mP_(WfyZ{M zsQ(MTaCZYiT2ej!?Nq@S$z2f@JXoDTy9qm^eid2nc4EHmb5T`+>pJviwg<8aI zx>oLmswY~#Vmn4eUr4BrSrzCxV2e*Qjq^R*l2Go%Ik&%Du(dkX+iYa#;~FAxG$x!S zzGU~nyWM)JJamRoO)1{U^E6zU+v}BhQwo0SCpY2Iq zLpnA76b9mnL7q~?N!goDYLAV z{|I1w`=-AV57AqGjk8xrB_;Ks<|{p&OM!V0=gpF%&o_5ZF4mpxv(Hwja79z8QRM!@ z9Wh2Y)-e3t#xM%1{C#Y|CTCPT!$&iTUVS40f|>^{M6d&XJLx9InKm5$E^=8;#^bfx z01r|#l=ig3%F7(KeZaiKSjA~0F2phz%77p+s2Klf8S70`apz$C{94xF{g<4|G{Y_K zyzzbqG?U2ZQ&C0jQ^<9B=^6)`K9xp^N1xDcR#6g&VP1t-$(9l72x?a<;Se8S&4Op* zxqG-*?*bvN5Z1iOACPd2AE>jpJ-4oYS>Q=N(RW`Vj;_B??C$Mp;|*Vs6n{b3E}>_w zLK=G!ypY6jBG3+|2g4j##lO^SpdP#)k?!rUernQZX+|)iZJn@c0#CoyY^_?}WZB?k z`}QC2{oi95>HsH8uoL)CzV-bzTnujj8y4ZC>?XIE);GqN=X`Y~Hl8u|Svq-1IbH^ULzYJmy67kS>O>=vSaTN*- zV&TMPsWrnyeik7MWCU*YeYvS#=U@wGE32w*7->Nkt}kS7&Sq1==kFfm9p*=bDaMV7 z^;I?IIQVX_<|*)0nF9dIyl@OHb*xe+gz{r69!!SszpJJ@hg)&1Vof}S9&7KL!H9R> z+tW6N=sgCD`lxlpz5JkX*B*o+(FTym@VX3#M zBqgH&J&dWgc-Gqp3t}#8;?Y=F|)3;+St3G3%;W;)_gn z)%(Wfv+P{#L2qz1oU-kiXl$iE>&&sqU%pT6$bBPGQ!BrTkuWG`srJ$BRS#Iw?ZdxZuFD`zuy<=!@BohyudXBH^+(88HqWT#WHK2INT zU`?f-MWt2HF^+n$v27)|=Vcx$zd7OWs2a*I zVTnA^f(3$IjH9rRY(=TQyz|V6LourSz~X6a zvM5oJdr9aepY@Sip%XLGgeT@q#3S_8z_%DvB`xgOfxQo3I?ukmzGHu)FDz2AHPK9i z%*2bY;POj5!d^s!qM?z9WR8{f?c3|Z*TXdxk_#$6M!9lW`Z&yT0Tb%?VhkztZbHg| z(=gop>tINR5{b+pXTj{?1#z4Kvscsk_k#XDmB6IYjBzc;U`*72Pr?f*bLcY-BCeuW zwpH?lUas~S85HxhA7$P@jy`2+yYd%(7wB#ifo@7gDvn!;aNwdUnO;eVa(qEchch3g zwN) zns+fj;X+<|dNSMY=;-&y-P5QauL{ms!+Bx!Dm2(-R;q?in~ZUizKys=dyaN99Rg4 z8$C5Gj(X9TX6+u&UMb-ok&UWG2^0Hx;b+yx)Z<~iH!CFffZ%{X**`#}0euNI6D>An5oo;Yf`Ie15Q zruqagkC;*h=(qWIz_kByYsw|ko9-0zvRSS@sFA~zpK zcPm7$MUq=}Si>rGY8h)Z-H77S3&zT}9nCHk)Bz!8H1ui*Q+Y4f{+D)Neik4NF{w$X zCN}g-igfi5_|sGz&I~qsn(g8hV@M^?-7H-+taKw@7Qy|v2q@|38xpN<-DB?9Krg9F z)Q?nGtNlrJzdlYd7ET!R-?-(#eQY2S?%OZ-n$j>>64sIfTZ--$fz)fvPg9 z%p=F!;x2NB0?%MjpVV_-1UVn#7G$b!$0{LFRt4D+gzBsa2-g>D1u zjv>os1wGoNau61Vn`goGbH&yf*VReJ1cx%tj7#uRg+xuBZEhNAW)AIEDjK}x7g)bA z2xC@%OQ|crhomkWSM9j6BbIyYHe5n`p6N!fGPJNzYZv7=@x8~{28x`J-tZ=1%^kcs z*Nni!SI}(%0OfLagKI0y{D@|j;0a>$JH*K;1?j5E1YW$IW^+#o3;F6EnfUGGSMP3{ zK^);)tcW?hKIW=9H5xrZ>7~9;zt9f{f-^)4aL7UamCXKrf+X($4LMT}V^aqgOM5$T zB?twL^$H#y9{ejp;Mc#tSis-fJDD@tTH2X9gM~Ou|N0}Tf62MU{_CCogzdjn-SWRx z-N*k+)jbosHRBgM`jg*R;lD-Qlp0B-d{D0``~}sGv~oVm8|gQD#zFq=@o6SS6`r|g``Wq>zQw-P`iCiht&9}6kSBm?I5-xL1xA^4qD10y~gP9 z<$K&2J2CnAa(|B5$#!HCEvPIe?eE6}Og$}U8?n*KFrI7C->SbKQQ$lktvF>FJ#NY% zJZ3Ayvd(Q3$7;-|(czUgCbq=JN7k}HDj?xD1Fr?~IPjt-8BBr`&%|bT-QQN zvFi-g=UEGIjxsNHnw(!UwZFK`02>dU(csP)cErXcRnHu1*Np@S+ga@X^jtH?)%2rY zWK0d0TaVQ*e#n*;TwGv-7ak*wTaY}M%Jg%8hV^gYi+ttwK_ zwyLeERIYBmF&~eu#Kfc`DwoT_whPxGYPe1wzC!MoZ))%stmWG%YQ%)uL=A1m9^QmM zh^b20djke5%djIOR_Gc*MmL#KAnH1qXGjY3bJ1~|sR~_pnY@rdB&4u)Ngg7e<*|eiqjO_vcQ+i5pF-_KOjt?x z^PtH^ZJPd462gAdb&j_UKK93A_}^zjtnZei1Vj@h%=V?TuK)<@Vx$j%S*d=CLH2!j zCIOAqg#9#`Ep)}*JFhq@I~ME{_0aY(Q7EB(bd*KpZSG`D_r6o6*(0#oeE^AeD4-dD zBaLh}3M2mp^c&-0V3ucozw<`_=*rUlGsb`4?f-R)lM-}okOWbJw{|Q5L29PCw5V2% zR9~Ix@2bLU#S+Mtp$ToHYd(r~UbG|EC9a@C4=F_m zbKw$Bv)l#mL*_~wD9E@3biUj@Mrw&!HL!eskrIS(Iia2+Mi39o;}H!rL;A79*NB9$ zqDW=)ii;a6GoFh7zH_Gq7lt&@W+*zGiDI( zGja?CH=l6aS=5xFQ)W&~?HJ56lBF$TJtH1aEG3QjDP!c%J=V@kB`bHGCC_Za<8U}T zPY1X|5I1Kf!&5}by&iJSGw~?QR2J+sEWZPom9?+NwcZc-pC6y1DHJe5)*EZT!fHFH z$T;Cut{leW(U#LzQw+@g!Tl;1JNl;o0bYwgy~Y1*x={Z&cy0c$TMqwVxS0R$6~T{n zPJhlY1N?QbU8aVIfc66BJ1&q85?pMsmZcj@X%K_WQdY|maZ|qJllOv=c5;eF!wo`lD zTaVmbx4e@huTvSV=-p_}e$b@0rW6Mh!khswzI>%GhVBOI{59{sp&Bp;=~03DPD~u0 zw8U6c7>g9Sk%0bRh|Gv11xiHvKb^)Ru@QZ~JqM2Ww?Jd*DA|w-m)eMrg(9n#EGqQv z3?ch;EWZsr)qJiG0I?(q-0NP`H0b&A(YoNb81js zBt&6xqLdT?avb(5(bfA`2B-ndxTy#;GBO1izk-}Xtintm5fKUNl=Ov+L_|WM(Q`EW zf^aNql5|{UZBrsL-<#S<$!j$9EgD<_8}ncyCwKCb zxihJek#g~%z+rRJ4FF&O?o626qc!%EH?=ZEM7%RwhU~*P4tA}dJz?oLUk8AOJUz#R~-$iv;aECd~sp= zA!m>y5T7U0RV2G$(xyg2Vmf2bEVUo8wO&c{=#F{tuUKFl&Iah2s)7~vKN$dsV3qXC z{5gvz6E@EB~P4lQYh^jSj+$Ro2vdCZnJ zO)C@9=0`%M!4{kkBRGc=(B(*64;G=eB7)z~(CuV|FxY1ik%-vS$iGD|PilwR$(S;5 zz)8GUQWJ@{&*Z`ui;fEa)Ux83jEntp)IcVZC(Ts>4rh6ngA&4_L=ZfBA9}|e?EUpP z!`@0jYq;oePR&S zv*~2l-NTie%?&GYDROroQZiomuzbCCUA0KvG`y(W8Dso@upGQc8$Yhi$rm0IcPlS7 z3O2a!2Cgjx?MfQb3Y$G`%RNMH=Z{mgEEdL(rFVRTx*?GDP?MB*9o+$XGb8~jr{qUn zH`TtIwN}=lNdBXr5>^?fm{C^JHVy=-peBa^4)*TB8J?*^R}^;jAKsu1i@zcUcZxBg1{? zQ813-Vc_AMAHl^ApvXeZ2HJPXZccnL3w6FA6M4R-K6%Gs#joW>A~F%XTZ+hI*4e-( zYa!P?KTR>_kCtcF7}vEfH6JGx0RnMY^_AQ|7F|5*OUK}x&n2({nJi<-A2SbJSSFkv zw&!CrMwyC}>vPc;4LyqAAO5mXz7;Fmy}dd(&;hOTT%YWs4j)6E@eYI81tO$bxJmSO zJ(5AoL8c=}md&M#P+(3)N(fGsM6VS^Z46fdvu{x72;X-)J)}u%rDknruDC~ixcf;` z_G~eQ6zU%_9B0YR32*vEUZU5S3>A?#SZ76J+>S08>%_cif~B${X*R*DH;p0RjQvf7 zeR5Yl{a0?9{V&l?*!R(E55){nq1*BN5OAN0bG{JtNYj@g6BwwZUtKeCdn2-n^AvwRyyi z$ju6DXt##C`eP|{Tyw&Bar03OawtvIA^EFVZ1@>pZ8(}8SCp8RYY14HB;dQ0Uzqo! znwb%qQ^^*VpeFYfeiB)#79?a70loN2);aGstW-nCLty1TpZ_ZG5z|SlT1DJDOJV zhULba&7z`!1C?G4(X1~*Z%?2cwLo8czmHh6oU_dWDsD1y z4BM-n({P7!Dm#iUlk>7zqh#60mGO#rtIp9T8+N2@TsIX!#x(CUuP7FOZ#Fa5T>R7- za9O6V+y*p?5^0Y;2nYwu$#cRgm+xaQ-zZe8&K;W6DvUBYu(X2N>U*@p1ty^cSdex$ zEmA&BZ6oPHO|9^jS7FsPG{v7pgvQ;weX?-)WPuuhl=CgpIO#<-JIk}uCGSK;PPY|n zJtd@qCd85x=wVm(!9XsjDc1ixrDccJCLBHa8{5Ij4kvGv=>0tUv;*kLik5(Un5XBO zJB<*f*_G_xXeG5IVs0%!aQ>o{a8qV%BeO*l^)?D$F+ znWOP3{k_lW;xOmP%$hIc?yZzLgver~6X**j$4YLc7E&+O+9+G9NWX~Sk>7JRmksqj zQDR``7Fb}nW+F(71!Sqm9jXtl&zQAmt+Yh4%zgiaSmTnX#2K* zI^`8PrZ}}_RWqP(+DYS?_rp2;yDN_fiX$rGMug-q`H+Ryn)`b3dmwOwV$F(%>P5d_ofPrP8ca zD3j>e;V3tXu*i?nebTfw7bTqx#Scnxf`RG*)qG+&!=3VsS-Ee%%c2)NMR7Jw zGoI61V|$GIQF;mjHmPt}k1ANN>f+YJG)ll_5F_5qXd`k}BWGQ8xYUOB z#zEp1`G4=esyQjrlcWI}iV@Z!rzI85USUgFM zXMZx_Im-t-Mvls8VjJl%$GzoxY;5Tuh;Px*IEi z^PwOGWAj&WwaVb;ce$N=RA?;Uxf-;=5C@cNitTMa77^Z*6QGt!Xk6l$~kG}cNDgP_aZWR=0+*EMhRQD9241o=&AcgvlD_Vzy7L_j1^n`@H% zSeRqQoBJ4-i2R}dh!OlO(=6{bWs=r5-<6py`r1-55LIuK5*IM!yk1Pd51r={hAuYV+ z6pXK*zD8ojNAxGMTwi}@H$#u%t=|BCr}6SP-No<57fqoxQMwjC=Nn(2T=#t7uJ>@e zzX133;(=8ZWEG(8g*gSP+}me~(=-6Psqv8+g`9tEnE6pC(715|Y6?MfQ8AA<7?B0tFbXalaHqn~x|aC<^7)K)pfZ^vi{ z&q0WLq12=YwMI0sO?S?l~UD@syG-Yf4z@^T-!-oKapUq*2J zJ6M+d=*ky11sGcVk4^5n3S)9Wj3^zVxL?AbWPW`@Ue?gXMi*h|(UTys+o@8fQ#fu| zZY6!Pp!@ZSe{>m>K&0(>qV*`_<@xRBFCbrV4tgQKo<=9+EQ){=9ZYNVf(l8u$Cbet z<;2@JF2z7Eu=`XEsH&jUD{mfQNtn^njNM@iN0=X26JM&X3Ru1^N?hV#?e;|(&uix1 z8EqhJC`q=PC@2L3A*A(K)x4(;?6eIfy3*{gM-O?{3~odbw^(RDM$Bpz!aQJ2&;>|g zqr(*v;4rpexe8PDs3(;2`6K#d{0Bo9PCXu1Csq!TtH^gZ9ng+_lG#W!0G!+Em zspNcG$lxDm5%fxA zZtVW(??67YMS5ZYJVDz&K>yCYc~@<{bACu<=HvN$iTq_w!v8OkzurXE=m~QmL4?5a zjpIRl5zoMkyLdvAks04uf;#ycOzgSzk;w7MP&Zb1J^?(bj0J+_5Gtt7yt7M34j|V7 z0`Z8e{a<3Qp$E^}74~ZclZ)oH;W%z?vYdDj`DN=#qlwP>$=Rr90>_Kb5lb^QN?4N6-)4Gd#pF1HmX#w}gWdvcqI^pt(L4XJ3V?ZD%aJ zk^2I#H>!>f^+RIAP3feW*N$^i)Az1-HwKYsq*sOBVSb;@U@lSO;D;7^{dj(#&HpjA zV-K)%0ysGSLu%(QHHm+}B52^?Xs>Vh@0lw?PG*)y|K`Od&A%!m31Wa>T@txNndE^2 zD8e-H#BGZ@q7tK4mRb7tWr|+gGuWHJLU5s(U)5RX*6xIT1bkHH>W6-U;cPSDG`CH8 zKcspkzrI{P;(waD;s}NiV-azRG>9a$>(^c{vwxgkEydw%GQ#kn(jjEW5Q|**hS^J* zMwmkknPgCZgsV)m%^Vcp(W=H-x^8iFjxH=|gH1E{fNR7=i_~fTYH9|g&QM60Yly`R z^Aox!>$dcSrJzyMOd@9O#;WZ#kFpFrdMIZ>9&P;Yt0=%nRvd{kSVNjcL{uf{*LaP- zPKIkYY4d|TuoQ5e`VUy#`WDHNh8FS`X>9e=uqN>k#3RRX;ywf?x2Ol(1&VA`6Lt4q zUK}ya>9_$RN;ZBn0I5Qnl1gPq#}a)AV{&5LjO{o5QWJn28E8`OLenXD!>URu(H4sZ z>X63}wd!dq<&xExdl$b|K@$~k1eFeCCq0Sp!Jd=xu(GLJgJqH=h6P04n|KO8l$ll&NO%dj&mjdJ2V|h=lLQm@o3D&XZiF-h zWjrg*wX<=58ca>8v94X^Gc%KC;OBg<4(bSw_{Hsc=7;+qn+^|~`5rF!Q(Zo9uzHxX zz{D^|ygqB@lIo6MB$sXm&J-MhEXprj+iPdAD+6cEAhxU8)N^(`g8Gqnh! z1cfIT>;-x2_Uok2s;-H?&#Gob_rF-5w{2B!y&N_Y0ro@h3$!39ioqqnQl z!QuCk6xj}UH-us07;{vDZX#A)xe*vZQmirT>bbUOTi#c3IgLqu%a=;j3_g1$St?+T z70=$_;8SDCW>}9hd#d&$)%MiZ!0s*V5b0CPf1Sp9O3W>o8gy|CVhWj3&BZZH3G1^3 z<+M>L0lRquB8SOfv4i@`l;V+W6%6brZVfXRWPntXwT_8=%Q41)^$gdyz;geoXO1vg z6+{%7lx8}=QW+9dMX%U^Eu?J?4K>-Zc`OX!oFed+DsbTL@Zl;Q`zc&s@NyloQ%)8d zJuwX(GrGSm*w3+|lJ-Td;0WMpxE&r=-ZIFLBW6vEeGvn~FoRXLI8A(5zeCf#P&p_A!WpU9Eud3U!CIXmu@T+ z(Q#!JY09EbHULoUIec>|3O1kb)NXO3=nN9yJ|p}1@lw9}%`~%M^vFKrMxYtj3UwJz zL6*0mu3)Z5L(;{nTI?0lMbg0)T|0PO?P>I7V!U^N`G^GYCwH&4VDDX;UE!Nukt07r z{SbHkE?*BcPWhQn8aYE2f*}UHR+psO=u_98D|+$VQ;^7~GgpZR@aIEQV`2mMME%pe z>48?3ge1MRA+_)@>ncm7WU13LmW2ZmB~_m2b0qKi68F-GGqYcfA{45qQqen*Sz-^E zS>g}mzi?K*UJ=#dG%k0BzMch|n2Mb5{!!%Eqd8Qn{_xp~|FJdnFC@!$V5S;t4G`yb6ecS06HQq)kc!Xj(7VN(Up!Geknp~BRcYjwy0W=aWB0X{t@J^@o) zhC`V6I78w-iF+%u1BhkHqHe=k^+(T{^yw4ds`2@NT7uF)_6x-eGR2_G!UXZYWu$+M z-*YH$Bwvju)OF$!U&Ig_P0FMZi<=<$Hbl9PdHAcFjXRpWw>a7aY*&*+$jo}^2Jg{X z7m>k8iw7kJ_?v#-TfVn2ShR_D*{%lOUYQOXlxU4Pv^>>WDi2vA>qOfm@U>8?lv~CC ziSR6(SB!q$<^y-p#Y+>l41no!)_{?R3g3z)5@2ZCGYZ$JbL;XkO(wI*3&Tl^$n++e zdS1pmy^Wj4cD~a_W|UlRnBgnFKS6JLoSgU*V(kQ5D46!JDlfBesSYPp0usf3=b_&F zV}4aD4@_krLvPh(kiTvJC>AYK=;|zd#VEZ2`^YT8*dq>5TwDDXn(oOoTYy_|p7q(& z;ozcQNRb&w(+~g!fwsDQBI$XD*x0JN0%oOQ)l!SKoUMP@ZvV=m{OORbP{kC0aq+C5 zy{#Vb9hZ-cs)2t3GVcB7yW&sqKHP*u|2(%1c&_Hw{j=z2d%o9$Vr_m7&oAupMkwub z>|(Qa6SAAUx$1pV3LKo?FkrtHFgeq)x2b1{d5(-9T zFfSEc9X=6OMlpZa)!{;ImS!5?r4pSmL&B)q`9AqwFpG%_m}MiM?yRL*B2C;J&Ew7{Eg2nMRFFy6}1o!eXt8QHbMn3^03XJqY#~-?8ZKm{c#$| z)zqLBAKyy+kAcEpQbGSd4OLr98-1fc6~X`TYyXRD^REet6aRy2lQ-WxJHLzcI_;nF zt3QzdVycvdnVhuoBVQO4CrChDOQXn7&PcDj#ZO7i+8UVY7ZoQ6T2A<*)U8xBjI>n2 z5CijRPFb3O4E&F=iA+q#rl!w&3)(PhIWZNhX>oqgz4l|{pHGwe4<&eGUwr8djP$?^ z)N;fz{i=*jwm;QkaQKlR1EYWV|KJeu9u`1FA4dTEk4NyAy6rz5fuxnK<-fe5sQ3xF zUIB!mcizv*X=C3;RfYq6USsvr{Ht>_e;7M{ytbh<3 zcWTW0n{izmf7jQoPm{KKgdy#aePW+Qg@{#%ZD`1e+~bku!;VBmYF%bx3=ZIT*JwIr zj2KYD6?l@6F|(0xoQl+QMmDm%H>PY@%^ZHI|fxjnbZFdu`yKfZi6G0(K!2Iu`c!jeTA^&}_; zVq+HrK%X{vljz@Ql{Q_>Tp%aaNL@-k!3Y`S%H(;b=Zk)7v?r*zttzA++#(!m^QAIj zTefh>Fs6A#-e=>}>ol7nTZ6i>lxEPYrDguSJTbrA%a+rTDAn%VlFZ19>wx}-N*g?`>>Yg@9yr$D1-kCR2%;@RP!u_ZWdqUm7C?I_a7-KfY5t>!k5aB4Oci8)pTCw^f+A8 ze>i$P!|tYhpg~b!(O;&>l{pqWoy;6j=#OD?OmdYI&1gB=<4}Af!QB5TN)=G55O@;? z1F#pPXyVR?T2x@vUn%J&7AMNH|w#P=rOd=DS}{4p8mVCH1r0%GnN;8k6M1C*IwjV?46a ztSFpndfmGk0HB)8wpu?~0&X*^>($-1j1yzduHE)N&)1BnVE6AD%>Q#BZKxra0DJ+kDfS;+Mxc&v2uDP2VDQj^Zb*_;jFvy}3Cpn! zTKw^Szc+^eJwE?7Me@6k?th-Ze*rWpZtXWfgWt{O28(JdE5+MyM)9V31XQmCauM1U z=3W|fPt8}4jrSZVDg4p-eBnvukPvC0Mw$A?yXv>j&pSK1+JTmbf`f2w$Y8KRQ6MuF zWHU-L!j82jaY(HV5zUTlG0YBP?lhC}2beIRMJaxaq|So}de*a2=zk_fPL5(a-;(%3 zGVdbgc5TTzh4z~wY9MZSUZ~OTMGT_-~LP1i(DNPjW)b<6vcMvoK*-xDc_5eT9|=mpkGusL>;)jhy&iKZ1M7f^1{ z8iV-@6JUq{jFE_t%m|VySjn|!zEYNQ&s(0yb+{I+>9UZgxLR&)RXPQ4u@J6lN89JU z%EZ{uiGj&7$F_+|v(|J9BXiW!$CQWT*kXy}+|p_xB8HO>vt!@qT$yH-3I{M-PfCp2 z)x1eIOq17HqFGvZPr>=-D)|kwAhOEhdmW+}7BW)Ra7(zP!B1_o9$S|Zo;(1AQbXSD zvISF>VcL1)>E~vPv^={PSxn|$IVb61hVjg`K=sPzFLtsfTQ!(KQ)TI7!j4f)Usy&( z=iIDNtm^ug%1HY*8E_)Hcn!NZc5p{4Urj!mg_FUP+wxr+(h0L?lAsAja7wpjgS5!A za1(}28X~%({K|0+4KY^PxV1&?ozikypf|Z%n zX@6k6d~?l$$KzZ@z{fB~%vs0-6lDu%TxN5at@NiNT{3u?CQ)eRu6aBm<~i_qKqbqv z69UN7LXDEh3|5S4!ur*3o?{OfiI}8t7-0-R`heULYmiz*vv_uHN;ucS`lG1zcLy7v z`lF7X2BOX&<9+bTip4@m^5VA`ugEfa2?@yy_CUgvBfZR^At9$31=Gw)8zd9(DEowL zG=vgnkGhLqy2W^xaeg>5pDoGe}}gmRZbt`g?|9< z0XrVQ-bK!4=+2G#xr7M*2z`5qIT$m^&{%B3L9J`!$x}qql@kf=3qzak4}my^KvTh}uLDt9^!i7klDUWMW^y&AG+Q z87+Qc^p%_Qp_SUL*2KPy+#xUBt<~fvK2+-s_O}f|_^dhidlqHsKk{Xn{$IEAPc15G z?Fg`U*8kHD%~aO@&6#~G0$uEF(&;xZSF2RXHE)gzqc33;jY?OLEil{N`vfefX>994 z@WB6bJ6%%NlWh>(C+-?XTG^oS3)u?iH_k22qx8(%gO?rhPw+LW1dMwIXpq4&>KI=! z5u;tZYg8Yoop7ByI#q~HB@cpjClo{mEpF80UAQ*Kmihcua0@Wnl?mlH;Tn)eCGaeV zs^*FNsiR0{>6mOWl^zS@4+#U5A6|#N0aHCdeHT6_gM!h7%~Rs*&@HF#^l2}701PCN zF%yotSt=$SO?la7P~j%I)NJ?{S;QYV#sXPFy3MXNL&9bkVGe?FQ0K!0v53I=mY8{%Xc&nld2Z4U!6tqNHfP(I?yDiql3J6#CZEJkrmNjt zToobP55U#`a^{>U%$MG44tCq}!vGU~L`!-P%$kd$twb+V|Ng100P7^{>U7VW0`&4K zd1mMH^|`$E*Rgx#oR(eYs#U*GDW^)0K0zm{3Vor{?+aU>UEslX-{JP+iw&vC8p8Azr%5bp)L-YO^6OK6FQ8;<$nT+TBo@wn8@`7!I+Hi z6pfE_Oop%Yv^hc+T~#)80Xs5v*+Zb&{e|KESsM9?%k6^7Q{+Y!FZ*_~nJ8l(e0)X5 zl1iEFTa&!Lf19}d;G&lI<5+ma^+`eA0$tokHW^Qwx`pYaT%@zSMQp3`T4iqC061Oa z`H!`vRSA(kEFadw>Cc+(f3_HZ>HYt=+IO&VvNr_$gTeS)H2?Xgn3*NuUoocgAAj{P zYmuZl_7PN}@B$}E(b|08iowmvkbVl9B9JemqvySBlGsf2eji# z1klLHI21cf@ji}wd3tsE0CDtW1w-Ufq2Nk~G8TXz=9_60ZLp_he!hH$sWsGxeorLS zqH5mL5Yq`NG6d!7%iVj3%B^X2p||WifH(Z{Gx#WSgO2^QcXx?+jM0M@l7XTbgpmaM z26ab5N>(&JmjhmRIlp%6M%NmSl_VA}e2l?Jstb9{3Y9Z>_NyojitXXu@i%jX7ki#_ z+sDy!5K;iP+)~485jBtx7}ZP4QR6kauj zv)2%o3o0Up&)k`YA3PLs(vj8O!n-e=j78r< z4K5=!f%0k1t<3Az`xW#)Qh`m)IPp2a{xD`(vEjormJjA>X$YaC1dO>@y6AxujU446 z=|;rv3_lOet-=H`#(W=}D#x5iVmF+g#K+-_3cL)WYQm&~*0xb3T!Ps^967-1g5i_U zsudrT^wZDG%b*EW%g7tfk&p_L!yQEywdn9~eE6EfCpiW73N1m7N->|BzsUs9W@e{a z2HB^~WqK~FOJnRoXqtW~#x{cwLB{^0 zAi4h^f>Z)nf0Qx-Mv_+gCja54W-43R%qn2;e*1>{J(>`k!3mgsOKVzHHWFU}nURjr zOl&t1a8ueX+kvb_gWmi~EvphK{l{X7IUxiV1A{aVo9t!>x$L8dmze6UPdvT6sE8t{ z{Ve^p{jq#aTPwy(&balPT!&U8HFpXvLVU)dr((omAn{Ntuw&C0KRh}O9|Fg~Z2~Qx ze_h1F7jRw$d#9&QwXW^(UCz5V^?iM4%i7?CAcnC+e8PZI8#c+7V7?n)Qb8%eXzE4T zNnKzb$$skeQo|p8Q^1qRUgJfj4kfeo+rQTpAHZ5fHDcY5H5mpgEH*R+f)KQD%HzKd zB6&{hOxb!~fHgp_V!lRLtOyRjmg*4=p5RYhT<6UF#`-Z@Mqkr?4kb9nnx&kIO#vp@ zHfaB3qHIQ?rZ0!y{K`|l`Td$vETAOI9al=X5yH-A*~0EUXyY`V+|bRcZLP)&aT(b} zrV|Y~7<|!3wzW6bz9qx#v+x)8BHRo}g|fp5mc(3B+6*q#k`HQbJAKd*97+m|h4T6{ zi;$)vtq0LlR`1uwA7BH^MPs<1o#NHVTDI>ZK%8;Z&AP-E@m3JI7G@zTRNg=igi{v4 zCy9S=79!}e3$Zd`nMU_<9Y)bkC{X|puuhb=W;AfTUg$(F((;1*+vR!saX5 zNF4b~i_rfvFMrh_NeL?-5hF_QyK-Y~#G=+&XLV(0D}v3sfJm+q%6j*h8F%swOQ~5I zU$Tq8Km4|E7_;F_f%$>}St|4U&o>9S@v*Z#W?xw&*gy#CXl*v?-or*}{dBsns@pV^ z#fe7seW?3 zO4RAR`qu06WoAsef1Pr>sSwDpjfKm3)PpXx^_VfX3Xm{i}VJ?fI=_>BLVVdjAZ|W{PnXP z=&?0e0g$hx%m^ODTuNM=<_3bkTqiUa{VmvUB)oghL{@!hBkq56G|>L4jT}A#N{4@P zG5$j)|Ic^+P0RSNUdn&{@GmE$Q3Fy3=cD7sr>&c2j0C|R!=Efxug;PnT^ktkfPw@8 z0ahZ-R5k?Q8@G{pac*f~z_aS!(Adn2w5H{einmyX3RAnVJg4P>|IlgC_y~ZvYTQas z)qTK#xLf+=U32-o`QFy`xXJVIt2E@(d5#!A&y^HKtYRpU&`Q#%ASsHX0dekT5A{Ng zB*kjg084$?Htamy(>Ae0m=Q+>8It#tB9UM+Bm6DoSg$(^OWqkVA}dS$v|%pYn`Ex5 zcoK-dU5-b%V78fQZQS7MD^Rh_AW$OnM(F4~_WJSnjjJ_cbCsyniXkGJ5|;!oy#N8Ueo!QpO8o>e{^^}QY7aWVfs)uf597$NF_4uBsDxAnP>ZP~ zLpomsUrJk>i{}BH+t5~D{Vwp{8L@mUA&r zPN*Z&2?DWfswJS~!*LOIHp*e^`;}S{+4dQm)H1#nQyU_}-p=I)zMR|gc!sWg4KroN zYVLXjr5i3+3=$pTP`U7q%?F+!J?^!J z++cF=u1aGEUCi&t3~^$EdkjPP8cPZ;&zih#phKh|6UldHa?!|UD}z~vbg(?RYBm*4 zvQt!>QSUA=_@zBiL9a|`r;O%i$7sAx>exUSceXdYlxgd=MW*+F=}R~@#F0$E1QLt| zqB1MQ8W1z_BnkcwfM@}=7s{pQIsV#JL>ac|o`A*>0w-P+NJeYQGz9tyW-K_dt%B2lxszSyxD{UsOa4g{VVJ6(GTiM3i5j=T96-oX?^P zdWu|Tr@$&gfZ40iuJ1&Ezsf2YuL-(dl`a%4%v9B@k0^x3MlR^>cE4lZ+uMK=a9)*L z6Bh{wxYF?p`lTH)P;sX3Ot%8G5En&(`RTz*9n+2^) z5GLxIX(fzNKcS4q8$=UD47fttwFW;rZscMFBivfk3BQVS@OQC1lE?xW@|udQa^RA- z(b@$Ev9HPGmIKY@DrFs(VMC#w(G>Y?NE;@AYB!;L+NyDj$8xn=i!5-33OK67*+J;79r{UHjRCp zwbrxD;Sm0E?d>Vh3l3NhLq3o2)Q7~&1a_VqPdzIuYFYKv7!{dm*MJ*k^pkwsE@3LN*WWStuFfnj8pfEEGGf1ef~5SyZ6Xs~&$pK+1Bus9PUos@?t0Scdk=4Mo9AS!8vXM|F0l zVG869C4Ohm>=)JSqJ%5j=ueLsBV8hBk7mS-og7%}TNw_BE1O#ge6V zC#}jG0nr9lCiJYDzML{j(6`Srq&$Ps4jAicXVaQs{VTR@wE0)Be)aa-+)ru*=oVpo zFL9$@ifx&X82tBKoWgE{l2}=5X^%uHfU2aT$&ow5%AWh~Owx?lIWD`P@n1S}_vi(O z9#JgBxjkQwWa9}#nGcT7bsqXxlHBMK;dx(nRWWKR515_Sif|SXNx3)*=KJS`S+OB3 zn5T4$li8fx5*@~>`(pxw=&)Ub0AJ3()2AP}_s;rqzj^l-uDxL2NIN7*OJ?g1$O59e zh3Ov4#(_>T``M&*=iRY`9MAEq5WYP(b)+9JB zz87s=sO!t2%HygZQyI~GR?k=|<)NwsHE6Xe(_5q=fa5TKp+BazJX2nXyQFIL?Lq&( z0%E;3cyV4;7S-0{oF@cC^K>utcn#isMw++PWt!F702kQ1tT0E!0#KIk-aAUEY+4)e zoPu@Qv>V!y2UGvzXg5R=W*m(-)lgDD;=D^o%7&td%)0TNFFA5b$Fh!1>nrtJv1t0i zxQE59`dXqyf&890TRO>p@qL3}UX-UzfoxzJkGZz{3)M;-Q(tYp4Oqypx{p4PRw_H% zqOQd#!Sc#0&Bvc%YM%6ecnmG%GdFH0&b}kYFwxi zVy^Z|f5Gz%8N%hIiXP|u2DvKanR^O+2~>}_5x;6)*pUe@(xLEN6FSEJH!LL zn?GRJL}NS(Wt-*uAR}4@^%D8DJv{t`9nStvT_};2)O1@ zk!M_({RrNC)W+iA|D%#IHI)J_w*^h&wA2mvL8#=x62)3#{CEN1kwK z=?Od9s@Y`UCF4%B3uFac5H3|#9zm2*q;#iW?$j>bsK?b1G-)<%TFw>Hz?}8PH_~Y@ z-f8ga%T_NSFVfUhwDxN{RG3xr4p=ntbO9o_^eNw=+_YLyQ-W}KQC$uoW{n_;)ml7?CbnE@=lirZ0u20Upe>m$&gPxOYQq|pC z1?qtDV!}w>Vk8xS8nOmTk>0NM>KnRBSLg5 z+#TrF<2W_$IkR3|v_|ti=MY#XaA5G$x^?pq!cGY-2|$kCYZF@J3(7Xm8`9a@TBFmI zaroSlO;-?#A6z(eg0C8~V;^5)QFg`hcYG3ty3^Riqg0 zs5=!}bapmpe+oX9NCdG)wwWL0lG>_N&YE@FRZ@!CA3hUE0E*>6Hl@D{QIo!ibkCwQ zMI)giXXjx=Vy@dFAb<^mL2T(f6YWxQz-<^cHhfIJ15K03tno5ZXMUB7V2$lFV z^R_vW(>RQ(uEnC{sKbv;UaDo-0{WYq&E+43+R!>0`iqY^YUCr@`uk)24@82$ImZ90 z(^mfG{wW~5$(c!(3KkG3{Xid3@`Hf-qNOO%Z7_qWuqnTW;BVGTLJ9W^#V2SIV)APH z>O97NJ)ua#jAHy)cxvUxkLE|-pZ72OqqrpbhaqYQwRG^JTt z)nOEErw5uj#iXG2z18;Zssy7166{XjT+aOT@7z;03FC*(Kl#)@=66$^dD3T6Ymkc8 z(@ZF!PSnZ(qM{#v>NajKj;WnUsKa2a&nL<*Ey`Z-n2c;kC*W;`6AexqIH*sYkZwc? zij@bZGp*W26I-}(e;92aU$Wxl2 z)|PhK=C-~K+R+lJv!-a2) zYN$CB%{_azLqcFKoH(HsWDUSQ7WR!T_C{FNO|zNh!IC26m_9SBShadlRJ`JZUB0*%?SI%p|C|V+f2?mECr2E49tT!-FFVws(okB8# z^2$y4J@rSc%4NS15spdNFg!~k($0wM7^8LnTFi`H_yaKs&!+D-tXq37aik})5i-h@ zd&;D90}^W_-1sc_TP(*d>RHMl%(i08RSFTpJk6^R-aUx?NOVrtPOFI-oS6|q?i9`R zfyG38V=TRgWSzQ5NR7ZETCGU&ut~7BK5rV=V25&~&%L8a-~?XRT7*>9@slEB`(Ry+ zx~C_}J#JXU_M5}@Fs3VL`RDDpi0!yfw!>39uyvaq4}Ubwp$AYD(0pXRbRqufCX)Yc z&f|||rvF`+RVt1B-b1HTJUuN$$YVobCwSmb-vR1gssaKPF4EO4+Z-2Rp&kwVKIjMk z0kQPNWHeEKVDPaAcW2`z?o0e?n@_gDLwv3^ z5Tt~f^dwDF#)KftWWYOtp)ZWUqhKoRr|U=btYA5lWTZqy&g99(3i67IBZ3uQjFljH z77vjbZ6nv@nAi#p*VU{`4(z2Sh(U|S4hj@$wX7rA6eBt65-P?fW9jCZ#z|Qc6N@=i zu06O9=8a^X#bNw^om~e!)!+NKCAU(@EPH3~xc1)3%*eV%_Lfm0Tf<1Q2}PlV ztc+x3k5aOdibxb`ssFj+>wa$cs^9DD6g4Z=oN|(#oacFycbjlh%cW~P zFoa)&Sz8Hl^lF_bx*E8?zu_C{yA!da#Kzgd9$(YV7lno8O7S)8jD#GryC%NB81er3 z?d>uHPU*|P7F|1RVigZ`B9h~bRmdz zrIP@Jr%+X9yiN7H8;IzgE={K~n^(wSVqb2}%~NeYMoF?F1gmmtO5AGLQ}@hpqQ4*vy{rS90p)a2QJXM!To< z1WD$|1^EmE4-I8{MVLc+yNmjae@lf4w;Ak4c}Y*lBlS1;xU*Vlh$4bTd3L|B)2WRK zBe z#260H%zdQeesi~}|Gg{qXD!AvOouxC9A{PUM6(gPt4-R`M5f!8zCU#%y*9ASgyOb9 zhGc(0WaW()6#iz6tBsP!E<0UiTjxpci}aS_EVMJ49Xs*rBG=oOHr+1-EF!(5;;CL| z%zKt89C1k~cM30V^Dr+eeM&v*{bfDJFeA1+o{?gGQM`XlMT2{Mdf#Dz7130lYo}aB z`96&LRvzp#m|5Rns+H8#8OU~ge*_y%t+)Na8+q$rdJIE~#p}NkE~#)0*)Wb*cnX<2 z)edM)Ste@MA+B2ZmWNS=`3)9*4+#%EW@pCKmeIb->!m}@^=fV<7aw<@NqsW^QUdK5 z3)Q;w+SJ27B_nuChqawRvKhVeYHaMq`DSHJ?pKn>Jbi2@l6x1+cxKh-%p)gEnWSTK z>Rkfp@}@qAoeHd2g&RIdo|RLc&{#8YX?_=RW%iLD{l2AZVSR?dq5MUai{95h!|x&- zO=W5GFP0^ZKg^Z!%r}64uR9UcL6K9}`92I$J>zxPkV{o|k25vm>=*a+(8rDwciYA# z-ApBilC1TpTwi$nun{#UJUR4gLGKOMmlVFt+3N-&&DI&Y5|5hhX#EoVN|fJK6YfZO zOXO^lz3hQ;^;b(@I%7zSOcD!@o>BfD!0pHM{6RQNXTu@-psE$umkTU2pvbM1NA3;YtOp z4`gv9^wX|7hq%4mrl-U6TXrr!$Akjb@^P?NlR)`PNtw9pZ)8QI1Q)$ zfrkwU&$Hj@FU)cC#=v<=M!6F1m~c)+F0~8Ekc2FAIr&e4q;=muQa3yl|FXB}?1q~G z2kD-6Mv!SsVDC;lA$HRq^9}w5eQjOv9XV6^ZWuEI-kIx`F!P0;aK;$g7Q7Pj_fif4pw2S@Qo_g_nQlD1Wmq~D_JY3{rn_@UDK1GlgX4MF= z9WTq$>t0~8Ve(?YB|1XR89z%W+HO#7e^$b#O3W%k&Q+y3H!aOL@mPDx&#udo1i)FP z!Bx0m*O4c5m!hk+%+gMs4IA5UqL?2=GmMD7^6rA0N!LiQi(k#4Hmm6vWk*7M({po$ zTT+v4m2dB8zErC15sRIOxwV&q(ku_S%2+R{d>&sVq=jX0>E=GC?)$)VJ{w1}=yCq(JQ33Ig9pm3 z_m(QFn7tlK9VmP0ZnnO3HYMw)$8tCKYDd9xVx)bKkhsI?&ll6^v*fOgu>DfGhQC*@ zRdAN}o#_LGa1J(+d+W3%x2qaAmJ5OEBroy^*R!5&|b2RKq(u055)-*Ww5 zjEDHG)r{Bu_~E;P-*mh_mg!M{x$TwdT`bH@+=>eEOwQm0H=zCGYfgG>3CLYMck^*@ zr>Co>pK)ioPKxMc6ItdH?eR?8XF9Lrq<*j%7lSk0tzdEEBW9HUo#6`Py3z+Pp75J@ z<*As_!9$+me356kdiw!zhSPL^MCRaFS##^)YV2Yg({=5KhBWW1+xmk}>oeajs?aHX z_bDGg&O&H7_EfDT2}xvg+V$r%e8x|8;yTjJjOZ<@`Et$L_N)l_5DMBwyFNE6m;x$1 zQhmNCd+1C1vslX&_1UZY+i_Yyod(cwIeKav=KkTz!>cL(%9(H51J!7qMSHUMcGrs*mkY6Av11K2r1w5&q$Wu+Q-R zgE_QDL3KB}3!Ue$xdvPc>7gg=w$u`$6OcaB2$!3$ExqQ$EXKATeD{`i;riNyc&R>2 zC0Qk1#D`9Qj;I$VB$+iXmG)L{Z8T2ZeOG8bkMbpb#;Lv#+dKR;_q(!I+Gf(OfvTP- z?-%=-T0Cv_@fp$fGot5=oa5aU{*q5YEt)u9Mw?_gx}R_50DDJb!C6&SRj2IEl?%G8 zEhH)N!K#|?-Dw#yl-eUR4g%aAjT=M z{6m8MBI{9hLBfE+5b2!V=S8#|FLS^jvBa|Ew+Bosr^)ZV7u`=xIs5rRA=inH`*4;Q z-ieB-HylY#@(q`+moC{gFrD5n z?Xj0$5})6e4M*B*zw`l|yAC&kEO{z?#dnj+tHR)-} zOu{GOjh{l!JUENfB%0wMzd!;i9c9F#V$fLL% zBMEJWtb-ctcq}zNOiO{j?cy}9LMgqiv7U2R4T8!_@{R_oei-m6Sg$h^iT@=dc#l~n z<u5Rv$=mYh+WK-Y7YsSMA#~`L=!o+O@_6|x#MG*;$h2gq`z_`2y!8#)+ zi}XEK7S6k@PdJ3d?}0!xOyOy0(LB3v8Nn~}iK!5&5ZM#$va+)xOw@w8Y}~zFe5dX0 z4HS0*_+h_$(Dr&Iozk- ztvRx$`&dJp5B#gGonA}n3o6bq7d#gHpukfkYUdN=brgq)m5nuQ)R~{j^wn1cJF5`& zPIa%;KS~^A&Z*kP;Nx5p5`AxwD4Wes&Uria^|{Zxn4O>CKPOqC{~axYAGeoi`Qt}qKn zWgR>{p|m&BZhSc-r@5a;`~vyU(D{}o&s7$gn>2;9^HpS3&U01#((9Cm%A`0_Xv|k0 z=_2tlCd;n zT2DRp$RDqjg;=$&W@ifCwzz3*k;eJX$HVejlDf=ljTyNqEx}D)jv~5y?T02z+$5`1 zc@vUXKdl&)rLIjnG@dIQg;lYN>stGHN_87;7q2Q5JDq=z40j;Sq)6>0_L0ztdK`sMNK0Wv|2+0J`a6;d^BVn~b{@+b?MH@jaYkX&F>rV#LH@-Ac@3~GTQia$B`V#ac^VHh zZ~j`K+*#yyO|mE+7S=&DAKGnaYX`KBJr1r)4*WLE1;i1eWS(!aO>2$;tFClM6@-1& zp$>0*)m2_GJ&w%N^^4pq;XIGR_v(v4oVv2VRG$MfObFi;LC`gk73S zFFUh4xS5;bNY=Vu3Orqzq~@l=VZTEE!W-X5;PBshxvfaLjuB9Y^%A$lGDYhVyd+?b z7U~|=AJK?p8_r;lI9|o8>evUo7C+Y4sSBHle0rK~wTquNIKGhAC;IUnSG?C6;$EWy4CZrTf&FcJM z>gF*yvZ1*7)NOPQ$DFe5+#VQ+(Jf)+sm9;~&lGt3Y`QX6RZ}{1{GN8&+*&u{IeH&9o|mll@!RS` zY1Yt(*0qK`g~jnornGE)Ya=l0g9h;7P=Vl@WW}MqrB8fT-SirLmh;n#64N|Q-#%Cr zvzZ;Ia2w#Of0=mo{QM!D=QF!Rg9JxsX6T6%C2Y+6l;5fN%US6WKqQ@RG2?$a~;E# zp5trl%u8gy{JEk|Fa}m)JV;U4c|FlyAdXBV@p!{ig2k_cu*IP<`c7PF#*o^M5SjFa z^EWT)>h2-D)PFiYtEJJyy3cbEKfSDYoiHwltUHN9sVNDR$_;IWXXHdBEmcw|^+yG$ z*@CYDCkO>q9}EJ&g?|6|W<}k%49z*JdX?lQ2UcWmFlK#`=M+<>>e4D=Ww4&T9r28d zR8ThZ#>(ok#lT~q2!kITIr!kr+&-jvc-a5wd2(PLKHfABv4>A+D;vo3s_UrmyIT7p z-1tFh3qIGa(iTWd0rQ(kEws~{r>y;~d2L;sK*Ze+K^S8H1B!>cE1!p#y9dI{#|h!B zd4#)DOH+$)S?g{O(yY+#?bPbwdHGs{|1m!=&h9r<1@o`%-xM5laCo!qb*11SrNf)I z&uQmr=4jp#eU~I62>KGW-ofc0&T~r&&_aC3Z+N5zu;IQ>rEOs#9KLve?Rn|rZB1h)0E>1yNyC0-L?xRHkpgR zZLH~aiACJrhbp6?&>>J{ddzr4w3I`;T_V=z<6U!?vFI=+rVEHf#j?rhBB#fst=C-D z%J2xzN?v4NWj+=BY&|MwQib%2!q3GawKO3%c**J&t?-IYewLn!qsjbE(_&K!Y62$} z^u6?@R0>PJ*o__a?c zD6hDS;{~o{#^e5~1gU(}roR?%K5(q&_9!$+!S|zrdDstIDP5hJ5U1AKHy)}g(Ew{D z7FJu6eX}ripgv}Vt_)w7Uhwes2a$BSQi-~gaIL|H?wO6xSa%!ZFIfN^u50r~2eYUm zow)yT=6FwmC=rhx1XlWg#`+hr9q8fi<>#FO!i%RbR|M?n2V>p!!_y1h(w3#=!+F!7 zGK`rmoCU5pZYA4(&T8K;GE2S<(LLE#ucrw}(gHv1Ry{H{_J3o*wgBsfZwT;$EZKxp z=ru>Rx#_q8J8#X@wvj>uqw^{KyT5#JJ*OS5Xgawezw{?6+&*>}n-o=3EMJF2vYHu;_0VfNw5rUvo$2 z#(NUl*1iy5i}1iFeqT!GoA1A87h>_6_Q)04pM2pP)HZGRjm5L~{psnU*kr)g-DX+mU^3z&Lol7?E26g%##vM9*>< z(2259dOEiCaNbCdp30GSe0P@25|<%BXC=7t(qVsMf?I+IrM*`lJ}Nh$xlLMUzc6<} zkS8^|NBgDL9{Ij+BXSRbn`1S{U=4FFUqReu;eqe7_8z)+KjNO@Pw*}|B<{`UJN-$- z`j^fl>H+BL@nih1l)w7fAPr!SAfJ;meGzLHy1Z~To z<~Qo^<0v{@PDib1EZ}7=;4?D>P7z%7V}yew0Y%3fXx27#1;%+Lm_TII;dVPjj)wO; zBFV>TGXfSJNmE>v?Ixh?6bzlRVNlfrLK(*Nr094&WqT*XfuUFqi;YMGg~6UB4@4z>NW82BS=_ zQ$=d*Fd@jmBx`|5 zh6>}+D_Fqv5%wTR+07P#d5RaWE;soB#4Iqy(8~myY0RrEAQ+QK;ed#WayBM7ZC@X28yCdi*B~LIyjB6Aa{|x_)qm1C zn1FQ<0b41oG4qkE=KUF@6ec348bYbib&P<%E-o8Bb34w??et)0WL^|^FyCwtRQ^It zsQ-QH!Oqgq8A{hh0ObKR5Y&teE5ZbcRIr$bjL#)vh@9(HFl1&3aka(RkkqWb9T8Y$ zM{gEna|f#qxs5PF@Uly=;b9*q-5Zhj$V3fufI27|0-P%#=FNuQM~)LD$-_ch+X+#_ zRe;t5mI-tft5#w{GXV19>xE^_5i;$^-L*NZP~nTI-T@5zSOwg4;l6;n+hDBFMLb=H z3GgopIxRW+(p4}4&EN+Wk-`SdaM;XwNoT7?6)@6yz&7Y4L^WbV!ahvY0`Xjcw(UmO zf(gyY+Qk>Sa~^kca04m}+jO8-$A-==c^hU}lv?xXTL)_0U+AK6?ZgO%R$d#4hs}He zC2LUHR5u#lb{SxFqEJijBEK1LH_9HYAlPdOqr; zlM;EIw%sQBv5o-Qh4-IDRCi)AHFmMyAd2Kqm~fxBzsa6=8$e%EYj_4tBhuLQPr@ov72Z zSSZ|*f=zhLJ2`4zXsBX6w}1tA6K}_h7t{pH&^rv@5B~)FhieczzftoSLzhK3IIlrA z`K>AYoiXKKxQ&`|7rLk;m;VQF>^Cr|d2NqC)}7!dY#m@ueB1LKjf?=YNKVQjTqjL$7u`zF>jhO5cgjV$_s{&`s~w z-=MH%0!8lvH3J>EsYGdefBc2oP5FjqLPX+Y;|A2u%lnB1e=~;}I;E(Y(V&!${RIhg zmOFHO)P!Bg{A$~+0tXlKI{%k!Yv|pe=43)<|JrULcsqCVmt0`z9igWDftoY8ggbZi zXTm2WHnv$sCJowdq{M$npsP5w<$42G$ zUbYi5YG@%;_xV!%D>77rpkCgg#>sJPvlcx4qQZub5*vqE>!HSgKnjCyf&eK2LI1F z2Fe^%9~9|r&VZ)_!v8Dw&MZRpp@7R!@)s-KXKsh&QlZ@{O$h$ D target; + private final String obfuscated; + private final String mapped; + + private NMSFields(Class target, String obfuscated, String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/NMSHandler_v1_19_R3.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/NMSHandler_v1_19_R3.java new file mode 100644 index 0000000..e05b5a0 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/NMSHandler_v1_19_R3.java @@ -0,0 +1,182 @@ +package com.ticxo.modelengine.v1_19_R3; + +import com.mojang.math.MatrixUtil; +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.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_19_R3.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_19_R3.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_19_R3.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_19_R3.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_19_R3.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_19_R3.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_19_R3.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_19_R3.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_19_R3.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.entity.Entity; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_19_R3 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + FriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, new ClientboundSetPassengersPacket(byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(mountId); + buf.writeVarInt(passengerIds.size()); + passengerIds.forEach(buf::writeVarInt); + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(buf); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/NMSMethods.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/NMSMethods.java new file mode 100644 index 0000000..0f5eaa3 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/NMSMethods.java @@ -0,0 +1,45 @@ +package com.ticxo.modelengine.v1_19_R3; + +import com.ticxo.modelengine.api.utils.ReflectionUtils.MethodEnum; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "d", "getInstrument", ItemStack.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityHandlerImpl.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..eb7ec93 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityHandlerImpl.java @@ -0,0 +1,687 @@ +package com.ticxo.modelengine.v1_19_R3.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.nms.entity.EntityHandler.BoxRelToCam; +import com.ticxo.modelengine.api.nms.entity.EntityHandler.InteractionResult; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_19_R3.NMSFields; +import com.ticxo.modelengine.v1_19_R3.NMSMethods; +import com.ticxo.modelengine.v1_19_R3.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_19_R3.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_19_R3.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_19_R3.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_19_R3.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_19_R3.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_19_R3.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_19_R3.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_19_R3.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_19_R3.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.minecraft.core.Holder; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.UseAnim; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.v1_19_R3.CraftWorld; +import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftItemStack; +import org.bukkit.craftbukkit.v1_19_R3.util.CraftLocation; +import org.bukkit.craftbukkit.v1_19_R3.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions((float)hitbox.getMaxWidth(), (float)hitbox.getHeight(), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + EntityUtils.nms(entity).setMaxUpStep((float)height); + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + double seatY = y + nmsEntity.getMyRidingOffset(); + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(entity.getEntityId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, data); + buf.writeByte(255); + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket(buf); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + if (oldNav instanceof WallClimberNavigation wallClimberNavigation) { + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + } else if (oldNav instanceof GroundPathNavigation groundPathNavigation) { + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + } else if (oldNav instanceof FlyingPathNavigation flyingPathNavigation) { + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + } else if (oldNav instanceof WaterBoundPathNavigation) { + newNav = new WaterBoundNavigationWrapper(mob); + } else { + if (!(oldNav instanceof AmphibiousPathNavigation amphibiousPathNavigation)) { + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var10) { + var10.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + ServerLevel level = ((CraftWorld)location.getWorld()).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + return EntityUtils.nms(entity).hurt(damageSource, amount); + } else { + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + } + + @Override + public InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case SUCCESS -> InteractionResult.SUCCESS; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.CONSUME_PARTIAL; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + default -> throw new IncompatibleClassChangeError(); + }; + } else { + return InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + FriendlyByteBuf pivotDataBuf = NetworkUtils.createByteBuf(); + pivotDataBuf.writeVarInt(DynamicHitbox.getPivotId()); + EntityUtils.writeData(pivotDataBuf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(pivotDataBuf, 8, EntityDataSerializers.FLOAT, 0.0F); + pivotDataBuf.writeByte(255); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket(pivotDataBuf); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + FriendlyByteBuf hitboxDataBuf = NetworkUtils.createByteBuf(); + hitboxDataBuf.writeVarInt(DynamicHitbox.getHitboxId()); + EntityUtils.writeData(hitboxDataBuf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(hitboxDataBuf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(hitboxDataBuf, 16, EntityDataSerializers.INT, 2); + hitboxDataBuf.writeByte(255); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(hitboxDataBuf); + FriendlyByteBuf mountBuf = NetworkUtils.createByteBuf(); + mountBuf.writeVarInt(DynamicHitbox.getPivotId()); + mountBuf.writeVarInt(1); + mountBuf.writeVarInt(DynamicHitbox.getHitboxId()); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket(mountBuf); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0 + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != UseAnim.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(player.getEntityId()); + EntityUtils.writeData(buf, 8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3)); + buf.writeByte(255); + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket(buf); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call(instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level, NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return new Vector3f(0.0F, (float)nmsEntity.getPassengersRidingOffset(), 0.0F); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = level.getChunkSource().chunkMap.entityMap; + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = lvl.getChunkSource().chunkMap.entityMap; + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3D(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + BoxRelToCam relX = BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + BoxRelToCam relY = BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + BoxRelToCam relZ = BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == BoxRelToCam.INSIDE && relY == BoxRelToCam.INSIDE && relZ == BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.REDSTONE, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityMetadataID.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityMetadataID.java new file mode 100644 index 0000000..cb5125c --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityMetadataID.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.v1_19_R3.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_TRANSLATION = 10; + public static final int DISPLAY_SCALE = 11; + public static final int DISPLAY_ROTATION_LEFT = 12; + public static final int DISPLAY_ROTATION_RIGHT = 13; + public static final int DISPLAY_BILLBOARD = 14; + public static final int DISPLAY_BRIGHTNESS = 15; + public static final int DISPLAY_VIEW_RANGE = 16; + public static final int DISPLAY_SHADOW_RADIUS = 17; + public static final int DISPLAY_WIDTH = 19; + public static final int DISPLAY_HEIGHT = 20; + public static final int DISPLAY_GLOW_COLOR = 21; + public static final int ITEM_DISPLAY_ITEM = 22; + public static final int ITEM_DISPLAY_TYPE = 23; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityUtils.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityUtils.java new file mode 100644 index 0000000..0993716 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/EntityUtils.java @@ -0,0 +1,27 @@ +package com.ticxo.modelengine.v1_19_R3.entity; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.syncher.EntityDataSerializer; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.v1_19_R3.entity.CraftEntity; + +public class EntityUtils { + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandle(); + } + + public static void writeData(FriendlyByteBuf byteBuf, int id, EntityDataSerializer serializer, T val) { + int serializedId = EntityDataSerializers.getSerializedId(serializer); + byteBuf.writeByte(id); + byteBuf.writeVarInt(serializedId); + serializer.write(byteBuf, val); + } + + public static void writeDataUnsafe(FriendlyByteBuf byteBuf, int id, EntityDataSerializer serializer, Object val) { + int serializedId = EntityDataSerializers.getSerializedId(serializer); + byteBuf.writeByte(id); + byteBuf.writeVarInt(serializedId); + serializer.write(byteBuf, val); + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/OcclusionClipContext.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/OcclusionClipContext.java new file mode 100644 index 0000000..7a9136d --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/OcclusionClipContext.java @@ -0,0 +1,115 @@ +package com.ticxo.modelengine.v1_19_R3.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.isOpaque() && state.getOcclusionShape(world, pos) == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (tX > 1.0 && tY > 1.0 && tZ > 1.0) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/TrackedEntityImpl.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..a48af75 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/TrackedEntityImpl.java @@ -0,0 +1,286 @@ +package com.ticxo.modelengine.v1_19_R3.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_19_R3.NMSFields; +import com.ticxo.modelengine.v1_19_R3.NMSMethods; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } + + @Override + public boolean isViewerSetUnchanged() { + if ((!this.mayHaveForced || this.forcedPairing.isEmpty() && this.forcedRemove.isEmpty()) && this.playerPredicate == DEFAULT_PREDICATE) { + if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } else { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(packet -> NetworkUtils.send(player.getUniqueId(), packet), nms); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/BodyRotationControlWrapper.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..a6862e3 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_19_R3.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/LookControlWrapper.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..162d629 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/LookControlWrapper.java @@ -0,0 +1,143 @@ +package com.ticxo.modelengine.v1_19_R3.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; +import org.spigotmc.ActivationRange; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/MoveControlWrapper.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..d36f86e --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/controller/MoveControlWrapper.java @@ -0,0 +1,247 @@ +package com.ticxo.modelengine.v1_19_R3.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.mount.controller.MountController.MountInput; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_19_R3.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.craftbukkit.v1_19_R3.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.isOnGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + controller.setInput(new MountInput()); + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/hitbox/HitboxEntityImpl.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..df75250 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,284 @@ +package com.ticxo.modelengine.v1_19_R3.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_19_R3.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_19_R3.entity.CraftEntity; +import org.bukkit.craftbukkit.v1_19_R3.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.v1_19_R3.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.v1_19_R3.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + private CraftEntity bukkitEntity; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public Iterable getArmorSlots() { + return this.armorItems; + } + + public ItemStack getItemBySlot(EquipmentSlot slot) { + return switch (slot.getType()) { + case HAND -> (ItemStack)this.handItems.get(slot.getIndex()); + case ARMOR -> (ItemStack)this.armorItems.get(slot.getIndex()); + default -> throw new IncompatibleClassChangeError(); + }; + } + + public void setItemSlot(EquipmentSlot slot, ItemStack stack) { + this.verifyEquippedItem(stack); + switch (slot.getType()) { + case HAND: + this.onEquipItem(slot, this.handItems.set(slot.getIndex(), stack), stack); + break; + case ARMOR: + this.onEquipItem(slot, this.armorItems.set(slot.getIndex(), stack), stack); + } + } + + public boolean isInvisible() { + return true; + } + + public void push(Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox() { + if (this.subHitbox == null) { + return super.makeBoundingBox(); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurt(DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurt(source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return this.bone.getActiveModel().getModeledEntity().getBase().hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, + entity, + new Vector(0, 0, 0), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + com.ticxo.modelengine.api.nms.entity.EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact( + this, + player.getBukkitEntity(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND + ); + + return switch (result) { + case SUCCESS, SUCCESS_NO_ITEM_USED -> InteractionResult.SUCCESS; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.CONSUME_PARTIAL; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }; + } + } + + public boolean shouldBeSaved() { + return false; + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public CraftEntity getBukkitEntity() { + if (this.bukkitEntity == null) { + this.bukkitEntity = new CraftLivingEntity(this.level.getCraftServer(), this) { + public org.bukkit.entity.EntityType getType() { + return org.bukkit.entity.EntityType.SILVERFISH; + } + }; + } + + return this.bukkitEntity; + } + + public void remove(RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level.getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/hitbox/OBB.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/hitbox/OBB.java new file mode 100644 index 0000000..9bba864 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_19_R3.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..bab65fb --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_19_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..7f85466 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_19_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/GroundNavigationWrapper.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..26ffbbf --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_19_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..79517a4 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_19_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..4ad16a0 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_19_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/ModelEngineChannelHandler.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..dda5a78 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/ModelEngineChannelHandler.java @@ -0,0 +1,452 @@ +package com.ticxo.modelengine.v1_19_R3.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.mount.controller.MountController.MountInput; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_19_R3.NMSFields; +import com.ticxo.modelengine.v1_19_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_19_R3.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntListIterator; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAddPlayerPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundAddPlayerPacket.class, this::handleAddPlayer) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost) + .registerPost(ClientboundAddPlayerPacket.class, this::handleAddPlayerPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + + for (Packet p : this.writeInterceptors.acceptPost(result)) { + list.add(p); + } + } + } + + if (!list.isEmpty()) { + Packet var13 = new ClientboundBundlePacket(list); + super.write(ctx, var13, promise); + } + } else { + Packet var14 = this.writeInterceptors.accept(packet); + if (var14 == null) { + return; + } + + Collection post = this.writeInterceptors.acceptPost(var14); + if (post.isEmpty()) { + super.write(ctx, var14, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var14); + + for (Packet p : post) { + list.add(p); + } + + Packet var15 = new ClientboundBundlePacket(list); + super.write(ctx, var15, promise); + } + } + } catch (Throwable var12) { + var12.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private ClientboundAddPlayerPacket handleAddPlayer(ClientboundAddPlayerPacket packet) { + int id = packet.getEntityId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private List handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List handleAddPlayerPost(ClientboundAddPlayerPacket packet) { + return this.handleMount(packet.getPlayerId()); + } + + private List handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + ArrayList list = new ArrayList<>(); + model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT).ifPresent(behaviorRenderer -> { + if (behaviorRenderer instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + CollectionDataTracker ids = mount.getPassengers(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(mount.getMountId()); + buf.writeVarInt(ids.size()); + ids.forEach(buf::writeVarInt); + list.add(new ClientboundSetPassengersPacket(buf)); + } + } + }); + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int size = buf.readVarInt(); + HashSet set = new HashSet<>(size); + + for (int i = 0; i < size; i++) { + int id = buf.readVarInt(); + this.markViewersDirty(id); + if (ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE) { + set.add(id); + } + } + + if (set.size() == size) { + return packet; + } else { + buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(set.size()); + + for (int id : set) { + buf.writeVarInt(id); + } + + return new ClientboundRemoveEntitiesPacket(buf); + } + } + + private > Packet handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int id = buf.readVarInt(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private > Packet handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(packet.id()); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, data); + } else { + EntityUtils.writeDataUnsafe(buf, item.id(), item.serializer(), item.value()); + } + } + + buf.writeByte(255); + packet = new ClientboundSetEntityDataPacket(buf); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int id = buf.readVarInt(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + if (!changed) { + return packet; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(packet.getVehicle()); + buf.writeVarInt(merged.size()); + IntListIterator var16 = merged.iterator(); + + while (var16.hasNext()) { + int idx = (Integer)var16.next(); + buf.writeVarInt(idx); + } + + return new ClientboundSetPassengersPacket(buf); + } + } + } + } + + private ServerboundInteractPacket handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int entityId = buf.readVarInt(); + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, packet) : packet; + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountInput input = controller.getInput(); + if (input == null) { + controller.setInput(new MountInput(inputPacket.getXxa(), inputPacket.getZza(), inputPacket.isJumping(), inputPacket.isShiftKeyDown())); + } else { + input.setSide(inputPacket.getXxa()); + input.setFront(inputPacket.getZza()); + input.setJump(inputPacket.isJumping()); + input.setSneak(inputPacket.isShiftKeyDown()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + return packet; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/NetworkHandlerImpl.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..c4e7e6f --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/NetworkHandlerImpl.java @@ -0,0 +1,140 @@ +package com.ticxo.modelengine.v1_19_R3.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_19_R3.NMSFields; +import com.ticxo.modelengine.v1_19_R3.network.utils.Bundler; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundPingPacket; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/patch/PatchedServerGamePacketListener.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..6d33be6 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,399 @@ +package com.ticxo.modelengine.v1_19_R3.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent.Action; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_19_R3.NMSMethods; +import java.util.Arrays; +import java.util.stream.Collectors; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.ActionType; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.v1_19_R3.CraftServer; +import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_19_R3.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().getLevel()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.getLevel(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + final ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + null + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT_ON, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + position + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT_ON, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + position + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.ATTACK, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch(new Handler() { + public void onInteraction(@NotNull InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND); + } + }); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE)) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelected().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + entity.getEntityData().resendPossiblyDesyncedEntity(player); + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem) { + entity.getEntityData().refresh(player); + if (entity instanceof Allay allay) { + connection.send( + new ClientboundSetEquipmentPacket( + entity.getId(), + Arrays.stream(net.minecraft.world.entity.EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.stripMeta(allay.getItemBySlot(slot), true))) + .collect(Collectors.toList()) + ) + ); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.getLevel()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.getLevel(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level.clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.tagMatches(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, org.bukkit.event.block.Action.RIGHT_CLICK_AIR, itemstack, enumhand + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent(CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacket packet, InteractionHand hand) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.getActionType() == ActionType.ATTACK, + hand == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..60e4041 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,63 @@ +package com.ticxo.modelengine.v1_19_R3.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper extends ServerboundInteractPacket { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, ServerboundInteractPacket original) { + super(NetworkUtils.readData(original)); + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + } + + public void write(FriendlyByteBuf var0) { + this.original.write(var0); + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/BulkEntityDataEncoder.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..c3bb816 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_19_R3.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/Bundler.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/Bundler.java new file mode 100644 index 0000000..a3b6f24 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_19_R3.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.get(this.bundles.size() - 1); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.get(this.bundles.size() - 1); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet p : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(p); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/NetworkUtils.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/NetworkUtils.java new file mode 100644 index 0000000..c607c01 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/NetworkUtils.java @@ -0,0 +1,271 @@ +package com.ticxo.modelengine.v1_19_R3.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler.LODTracker; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_19_R3.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.util.Collection; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static FriendlyByteBuf createByteBuf() { + return new FriendlyByteBuf(Unpooled.buffer()); + } + + public static FriendlyByteBuf createByteBuf(Consumer consumer) { + FriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static FriendlyByteBuf readData(Packet packet) { + FriendlyByteBuf buf = createByteBuf(); + packet.write(buf); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + FriendlyByteBuf buf = createByteBuf(); + buf.writeVarInt(id); + buf.writeDouble(pos.x); + buf.writeDouble(pos.y - 0.375); + buf.writeDouble(pos.z); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + ClientboundTeleportEntityPacket tpHigher = new ClientboundTeleportEntityPacket(buf); + buf = createByteBuf(); + buf.writeVarInt(id); + buf.writeDouble(pos.x); + buf.writeDouble(pos.y - 0.5); + buf.writeDouble(pos.z); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + ClientboundTeleportEntityPacket tpLower = new ClientboundTeleportEntityPacket(buf); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Packets.PacketSupplier lodWrapper(ModeledEntity modeledEntity, BiFunction> packetFunction) { + return uuid -> { + LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/PacketInterceptor.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..0d9ae0b --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/PacketInterceptor.java @@ -0,0 +1,83 @@ +package com.ticxo.modelengine.v1_19_R3.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor { + private final Map, PacketInterceptor.Modifier> registry = Maps.newConcurrentMap(); + private final Map, PacketInterceptor.Listener> postRegistry = Maps.newConcurrentMap(); + + public PacketInterceptor register(Class clazz, Function function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public PacketInterceptor registerPost(Class clazz, Function> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor.Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor.Listener listener = this.postRegistry.get(original.getClass()); + return (Collection)(listener != null ? listener.listen(original) : List.of()); + } + } + + static class Listener { + private final Class clazz; + private final Function> function; + + public Collection listen(Packet original) { + try { + Collection collection = this.function.apply(this.clazz.cast(original)); + return (Collection)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(Class clazz, Function> function) { + this.clazz = clazz; + this.function = function; + } + } + + static class Modifier { + private final Class clazz; + private final Function function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(Class clazz, Function function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/Packets.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/Packets.java new file mode 100644 index 0000000..b5dda41 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_19_R3.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/HeldItemParser.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..c446d63 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/HeldItemParser.java @@ -0,0 +1,202 @@ +package com.ticxo.modelengine.v1_19_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer.Item; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.v1_19_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.Packets; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftItemStack; +import org.joml.Quaternionf; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size()); + destroy.forEach((s, item) -> buf.writeVarInt(item.getId())); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Map items = renderer.getRendered(); + buf.writeVarInt(1 + items.size()); + buf.writeVarInt(renderer.getId()); + items.forEach((s, item) -> buf.writeVarInt(item.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)16); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + if (spawn) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, 1); + EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, this.viewRange); + } else if (renderer.isTransformDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + renderer.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), spawn); + renderer.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 21, EntityDataSerializers.INT, color), spawn); + renderer.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 10, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getRotation() + .ifDirty( + quaternionf -> EntityUtils.writeData(buf, 12, EntityDataSerializers.QUATERNION, quaternionf.rotateY((float) Math.PI, new Quaternionf())), spawn + ); + renderer.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), spawn); + renderer.getDisplay() + .ifDirty(display -> EntityUtils.writeData(buf, 23, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(location.getX(), location.getY(), location.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + buf.writeDouble(location.getX()); + buf.writeDouble(location.getY()); + buf.writeDouble(location.getZ()); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + return new ClientboundTeleportEntityPacket(buf); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + CollectionDataTracker set = renderer.getPassengers(); + buf.writeVarInt(set.size()); + set.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/LeashParser.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/LeashParser.java new file mode 100644 index 0000000..94e35a7 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/LeashParser.java @@ -0,0 +1,176 @@ +package com.ticxo.modelengine.v1_19_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer.Leash; +import com.ticxo.modelengine.v1_19_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Map leashes = renderer.getRendered(); + buf.writeVarInt(leashes.size()); + leashes.forEach((s, leash) -> buf.writeVarInt(leash.getLeashId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos); + } + + private ClientboundAddEntityPacket leashSpawn(Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.SLIME, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getLeashId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetEntityDataPacket leashData(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getLeashId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, 0); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket mount(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(buf); + } + + private Object move(Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos); + } + } + + private ClientboundSetEntityLinkPacket link(Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeInt(renderer.getLeashId()); + buf.writeInt(renderer.getConnected().get()); + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(buf); + } + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/MountParser.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/MountParser.java new file mode 100644 index 0000000..a36dda8 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/MountParser.java @@ -0,0 +1,244 @@ +package com.ticxo.modelengine.v1_19_R3.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer.Mount; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_19_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.AttributeSnapshot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, mount) -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getMountId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection mounts = renderer.getRendered().values(); + buf.writeVarInt(mounts.size() * 2); + mounts.forEach(mount -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getMountId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(Mount renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket mountSpawn(Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)16); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket pivotMount(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getMountId()); + return new ClientboundSetPassengersPacket(buf); + } + + private ClientboundSetPassengersPacket mount(Mount renderer) { + CollectionDataTracker ids = renderer.getPassengers(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + buf.writeVarInt(ids.size()); + ids.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Packets.PacketSupplier pivotMove(Mount renderer) { + return NetworkUtils.createPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(Mount renderer) { + FriendlyByteBuf rot = NetworkUtils.createByteBuf(); + rot.writeVarInt(renderer.getMountId()); + rot.writeByte(renderer.getYaw().get()); + rot.writeByte(0); + rot.writeBoolean(false); + return Rot.read(rot); + } + + private ClientboundSetEntityDataPacket mountHealth(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, renderer.getHealth().get()); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection attributes = Lists.newArrayList(); + attributes.add(new AttributeSnapshot(Attributes.MAX_HEALTH, renderer.getMaxHealth().get().floatValue(), Lists.newArrayList())); + buf.writeVarInt(renderer.getMountId()); + buf.writeCollection(attributes, (buf2, attribute) -> { + buf2.writeResourceLocation(BuiltInRegistries.ATTRIBUTE.getKey(attribute.getAttribute())); + buf2.writeDouble(attribute.getBase()); + buf2.writeCollection(attribute.getModifiers(), (buf3, modifier) -> { + buf3.writeUUID(modifier.getId()); + buf3.writeDouble(modifier.getAmount()); + buf3.writeByte(modifier.getOperation().toValue()); + }); + }); + return new ClientboundUpdateAttributesPacket(buf); + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/NameTagParser.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..46be7fd --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/NameTagParser.java @@ -0,0 +1,196 @@ +package com.ticxo.modelengine.v1_19_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer.NameTag; +import com.ticxo.modelengine.v1_19_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Component.Serializer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, mount) -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getTagId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection nameTags = renderer.getRendered().values(); + buf.writeVarInt(nameTags.size() * 2); + nameTags.forEach(nameTag -> { + buf.writeVarInt(nameTag.getPivotId()); + buf.writeVarInt(nameTag.getTagId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + if (spawn) { + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + } + + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getTagId()); + renderer.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), spawn); + renderer.getTranslate().ifDirty(vector3f -> EntityUtils.writeData(buf, 10, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getTextOpacity().ifDirty(flag -> EntityUtils.writeData(buf, 26, EntityDataSerializers.BYTE, flag), spawn); + renderer.getBackgroundColor().ifDirty(flag -> EntityUtils.writeData(buf, 25, EntityDataSerializers.INT, flag), spawn); + renderer.getLineWidth().ifDirty(flag -> EntityUtils.writeData(buf, 24, EntityDataSerializers.INT, flag), spawn); + renderer.getStyle().ifDirty(flags -> EntityUtils.writeData(buf, 27, EntityDataSerializers.BYTE, flags), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new IncompatibleClassChangeError(); + }; + EntityUtils.writeData(buf, 14, EntityDataSerializers.BYTE, value); + }, spawn); + renderer.getJsonString().ifDirty(jsonString -> { + if (jsonString == null) { + EntityUtils.writeData(buf, 23, EntityDataSerializers.COMPONENT, Component.empty()); + } else { + EntityUtils.writeData(buf, 23, EntityDataSerializers.COMPONENT, Serializer.fromJson(jsonString)); + } + }, spawn); + renderer.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 15, EntityDataSerializers.INT, val), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object pivotMove(NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTag renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getTagId()); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/SegmentParser.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..63d418f --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/SegmentParser.java @@ -0,0 +1,224 @@ +package com.ticxo.modelengine.v1_19_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer.Pivot; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer.SegmentDisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayBone.BoneData; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_19_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftItemStack; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentDisplayBone bone : pivot.getRendered().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + HashSet destroy = new HashSet<>(); + + for (Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeCollection(destroy, FriendlyByteBuf::writeVarInt); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket pivotMount(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + buf.writeCollection(pivot.getPassengers(), FriendlyByteBuf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Object pivotTeleport(Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(Pivot pivot, BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + if (force) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } else if (bone.isTransformDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, flag ? 0 : 1), force); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), force); + bone.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 21, EntityDataSerializers.INT, color), force); + bone.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 15, EntityDataSerializers.INT, val), force); + bone.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 10, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty( + quaternionf -> EntityUtils.writeData(buf, 12, EntityDataSerializers.QUATERNION, quaternionf.rotateY((float) Math.PI, new Quaternionf())), + force || TMath.getBit(update, 1) + ); + bone.getRightRotation() + .ifDirty(quaternionf -> EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> EntityUtils.writeData(buf, 14, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), force); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), force); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 23, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), force); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + return new ClientboundSetEntityDataPacket(buf); + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/SubHitboxParser.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..fda2882 --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/behavior/SubHitboxParser.java @@ -0,0 +1,163 @@ +package com.ticxo.modelengine.v1_19_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer.SubHitbox; +import com.ticxo.modelengine.v1_19_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, subHitboxx) -> { + buf.writeVarInt(subHitboxx.getPivotId()); + buf.writeVarInt(subHitboxx.getHitboxId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection subHitboxes = renderer.getRendered().values(); + buf.writeVarInt(subHitboxes.size() * 2); + subHitboxes.forEach(subHitbox -> { + buf.writeVarInt(subHitbox.getPivotId()); + buf.writeVarInt(subHitbox.getHitboxId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitbox renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private Object pivotMove(SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitbox renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getHitboxId()); + return new ClientboundSetPassengersPacket(buf); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getHitboxId()); + renderer.getWidth().ifDirty(width -> EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, width), spawn); + renderer.getHeight().ifDirty(height -> EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, height), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/model/DisplayParser.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/model/DisplayParser.java new file mode 100644 index 0000000..82fe03e --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/model/DisplayParser.java @@ -0,0 +1,735 @@ +package com.ticxo.modelengine.v1_19_R3.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler.LODTracker; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.model.render.DisplayBone.BoneData; +import com.ticxo.modelengine.api.model.render.DisplayRenderer.Hitbox; +import com.ticxo.modelengine.api.model.render.DisplayRenderer.Pivot; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_19_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static Constructor CUSTOM_PAYLOAD_CONSTRUCTOR; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size()); + destroy.forEach(buf::writeVarInt); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitboxDestroy.size()); + hitboxDestroy.forEach(buf::writeVarInt); + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)u -> this.displayData(u, null, boneData, false, transformOnly)); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(FriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CONSTRUCTOR == null) { + CUSTOM_PAYLOAD_CONSTRUCTOR = ClientboundCustomPayloadPacket.class.getDeclaredConstructor(FriendlyByteBuf.class); + CUSTOM_PAYLOAD_CONSTRUCTOR.setAccessible(true); + } + + return (Packet)CUSTOM_PAYLOAD_CONSTRUCTOR.newInstance(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData(BulkEntityDataEncoder encoder, UUID uuid, @Nullable LODTracker tracker, BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(Pivot pivot) { + return pivot.isOverridden() ? null : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Pivot pivot) { + if (pivot.isOverridden()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundSetPassengersPacket pivotMount(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + buf.writeVarInt(pivot.getPassengers().size()); + pivot.getPassengers().forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Object pivotTeleport(Pivot pivot) { + return !pivot.getPosition().isDirty() ? null : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + + private ClientboundAddEntityPacket displaySpawn(Pivot pivot, BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, @Nullable LODTracker tracker, BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + if (!force && update != 0) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + EntityUtils.writeData(buf, 21, EntityDataSerializers.INT, color); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + EntityUtils.writeData(buf, 15, EntityDataSerializers.INT, val); + } + }, force); + bone.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 10, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty( + quaternionf -> EntityUtils.writeData(buf, 12, EntityDataSerializers.QUATERNION, quaternionf.rotateY((float) Math.PI, new Quaternionf())), + force || TMath.getBit(update, 1) + ); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + EntityUtils.writeData(buf, 14, EntityDataSerializers.BYTE, (byte)billboard.ordinal()); + } + }, force); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), force); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), force); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 23, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), force); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetEntityDataPacket displayVisibleData(BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))); + bone.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 21, EntityDataSerializers.INT, color)); + bone.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 15, EntityDataSerializers.INT, val)); + bone.getBillboard().ifDirty(billboard -> EntityUtils.writeData(buf, 14, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 23, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundAddEntityPacket hitboxSpawn(Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getHitboxId()); + hitbox.getWidth().ifDirty(val -> EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, val), spawn); + hitbox.getHeight().ifDirty(val -> EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, val), spawn); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getShadowId()); + hitbox.getShadowRadius().ifDirty(val -> EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, val), spawn); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(14, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(15, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(10, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(16, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getPivotId()); + buf.writeVarInt(passengers.size()); + passengers.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + } +} diff --git a/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/vfx/VFXDisplayParser.java b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..efc240a --- /dev/null +++ b/nms/v1_19_R3/src/main/java/com/ticxo/modelengine/v1_19_R3/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,142 @@ +package com.ticxo.modelengine.v1_19_R3.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer.VFXModel; +import com.ticxo.modelengine.v1_19_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_19_R3.network.utils.Packets; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(2); + buf.writeVarInt(vfx.getPivotId()); + buf.writeVarInt(vfx.getModelId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXModel vfx) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getModelId()); + if (spawn) { + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, 1); + EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, 4096.0F); + EntityUtils.writeData(buf, 23, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal()); + } else if (vfx.isModelDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + vfx.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 10, EntityDataSerializers.VECTOR3, vector3f), spawn); + vfx.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), spawn); + vfx.getLeftRotation() + .ifDirty( + quaternionf -> EntityUtils.writeData(buf, 12, EntityDataSerializers.QUATERNION, quaternionf.rotateY((float) Math.PI, new Quaternionf())), spawn + ); + vfx.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), spawn); + vfx.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 15, EntityDataSerializers.INT, val), spawn); + buf.writeByte(255); + vfx.clearModelDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object teleport(VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXModel vfx) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(vfx.getModelId()); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSFields.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSFields.java new file mode 100644 index 0000000..bb53767 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSFields.java @@ -0,0 +1,57 @@ +package com.ticxo.modelengine.v1_20_R1; + +import com.ticxo.modelengine.api.utils.ReflectionUtils.ReflectionEnum; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionEnum { + ENTITY_dimensions(Entity.class, "bh", "dimensions"), + ENTITY_eyeHeight(Entity.class, "bi", "eyeHeight"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "cb", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "bk", "jumping"), + MOB_lookControl(Mob.class, "bK", "lookControl"), + MOB_moveControl(Mob.class, "bL", "moveControl"), + MOB_navigation(Mob.class, "bN", "navigation"), + MOB_goalSelector(Mob.class, "bO", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "bT", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "G", "clientIsFloating"), + SERVER_GAME_PACKET_LISTENER_IMPL_connection(ServerGamePacketListenerImpl.class, "h", "connection"), + MOVE_CONTROL_operation(MoveControl.class, "k", "operation"), + TRACKED_ENTITY_serverEntity(TrackedEntity.class, "b", "serverEntity"), + TRACKED_ENTITY_range(TrackedEntity.class, "d", "range"), + LEVEL_threadSafeRandom(Level.class, "f", "threadSafeRandom"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "a", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "a", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(Class target, String obfuscated, String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSHandler_v1_20_R1.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSHandler_v1_20_R1.java new file mode 100644 index 0000000..161b428 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSHandler_v1_20_R1.java @@ -0,0 +1,182 @@ +package com.ticxo.modelengine.v1_20_R1; + +import com.mojang.math.MatrixUtil; +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.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_20_R1.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_20_R1.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R1.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_20_R1.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_20_R1.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_20_R1.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_20_R1.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_20_R1.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_20_R1.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.entity.Entity; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_20_R1 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + FriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, new ClientboundSetPassengersPacket(byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(mountId); + buf.writeVarInt(passengerIds.size()); + passengerIds.forEach(buf::writeVarInt); + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(buf); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSMethods.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSMethods.java new file mode 100644 index 0000000..9937ef2 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/NMSMethods.java @@ -0,0 +1,45 @@ +package com.ticxo.modelengine.v1_20_R1; + +import com.ticxo.modelengine.api.utils.ReflectionUtils.MethodEnum; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "d", "getInstrument", ItemStack.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityHandlerImpl.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..68ef0b1 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityHandlerImpl.java @@ -0,0 +1,687 @@ +package com.ticxo.modelengine.v1_20_R1.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.nms.entity.EntityHandler.BoxRelToCam; +import com.ticxo.modelengine.api.nms.entity.EntityHandler.InteractionResult; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_20_R1.NMSFields; +import com.ticxo.modelengine.v1_20_R1.NMSMethods; +import com.ticxo.modelengine.v1_20_R1.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_20_R1.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_20_R1.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_20_R1.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_20_R1.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_20_R1.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_20_R1.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_20_R1.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_20_R1.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_20_R1.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.minecraft.core.Holder; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.UseAnim; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.v1_20_R1.CraftWorld; +import org.bukkit.craftbukkit.v1_20_R1.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_20_R1.inventory.CraftItemStack; +import org.bukkit.craftbukkit.v1_20_R1.util.CraftLocation; +import org.bukkit.craftbukkit.v1_20_R1.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions((float)hitbox.getMaxWidth(), (float)hitbox.getHeight(), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + EntityUtils.nms(entity).setMaxUpStep((float)height); + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + double seatY = y + nmsEntity.getMyRidingOffset(); + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(entity.getEntityId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, data); + buf.writeByte(255); + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket(buf); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + if (oldNav instanceof WallClimberNavigation wallClimberNavigation) { + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + } else if (oldNav instanceof GroundPathNavigation groundPathNavigation) { + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + } else if (oldNav instanceof FlyingPathNavigation flyingPathNavigation) { + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + } else if (oldNav instanceof WaterBoundPathNavigation) { + newNav = new WaterBoundNavigationWrapper(mob); + } else { + if (!(oldNav instanceof AmphibiousPathNavigation amphibiousPathNavigation)) { + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var10) { + var10.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + ServerLevel level = ((CraftWorld)location.getWorld()).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + return EntityUtils.nms(entity).hurt(damageSource, amount); + } else { + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + } + + @Override + public InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case SUCCESS -> InteractionResult.SUCCESS; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.CONSUME_PARTIAL; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + default -> throw new IncompatibleClassChangeError(); + }; + } else { + return InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + FriendlyByteBuf pivotDataBuf = NetworkUtils.createByteBuf(); + pivotDataBuf.writeVarInt(DynamicHitbox.getPivotId()); + EntityUtils.writeData(pivotDataBuf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(pivotDataBuf, 8, EntityDataSerializers.FLOAT, 0.0F); + pivotDataBuf.writeByte(255); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket(pivotDataBuf); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + FriendlyByteBuf hitboxDataBuf = NetworkUtils.createByteBuf(); + hitboxDataBuf.writeVarInt(DynamicHitbox.getHitboxId()); + EntityUtils.writeData(hitboxDataBuf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(hitboxDataBuf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(hitboxDataBuf, 16, EntityDataSerializers.INT, 2); + hitboxDataBuf.writeByte(255); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(hitboxDataBuf); + FriendlyByteBuf mountBuf = NetworkUtils.createByteBuf(); + mountBuf.writeVarInt(DynamicHitbox.getPivotId()); + mountBuf.writeVarInt(1); + mountBuf.writeVarInt(DynamicHitbox.getHitboxId()); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket(mountBuf); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0 + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != UseAnim.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(player.getEntityId()); + EntityUtils.writeData(buf, 8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3)); + buf.writeByte(255); + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket(buf); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call(instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return new Vector3f(0.0F, (float)nmsEntity.getPassengersRidingOffset(), 0.0F); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = level.getChunkSource().chunkMap.entityMap; + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = lvl.getChunkSource().chunkMap.entityMap; + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3D(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + BoxRelToCam relX = BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + BoxRelToCam relY = BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + BoxRelToCam relZ = BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == BoxRelToCam.INSIDE && relY == BoxRelToCam.INSIDE && relZ == BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.REDSTONE, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityMetadataID.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityMetadataID.java new file mode 100644 index 0000000..a010c14 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityMetadataID.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.v1_20_R1.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_TRANSLATION = 10; + public static final int DISPLAY_SCALE = 11; + public static final int DISPLAY_ROTATION_LEFT = 12; + public static final int DISPLAY_ROTATION_RIGHT = 13; + public static final int DISPLAY_BILLBOARD = 14; + public static final int DISPLAY_BRIGHTNESS = 15; + public static final int DISPLAY_VIEW_RANGE = 16; + public static final int DISPLAY_SHADOW_RADIUS = 17; + public static final int DISPLAY_WIDTH = 19; + public static final int DISPLAY_HEIGHT = 20; + public static final int DISPLAY_GLOW_COLOR = 21; + public static final int ITEM_DISPLAY_ITEM = 22; + public static final int ITEM_DISPLAY_TYPE = 23; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityUtils.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityUtils.java new file mode 100644 index 0000000..e96dbe6 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/EntityUtils.java @@ -0,0 +1,27 @@ +package com.ticxo.modelengine.v1_20_R1.entity; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.syncher.EntityDataSerializer; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.v1_20_R1.entity.CraftEntity; + +public class EntityUtils { + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } + + public static void writeData(FriendlyByteBuf byteBuf, int id, EntityDataSerializer serializer, T val) { + int serializedId = EntityDataSerializers.getSerializedId(serializer); + byteBuf.writeByte(id); + byteBuf.writeVarInt(serializedId); + serializer.write(byteBuf, val); + } + + public static void writeDataUnsafe(FriendlyByteBuf byteBuf, int id, EntityDataSerializer serializer, Object val) { + int serializedId = EntityDataSerializers.getSerializedId(serializer); + byteBuf.writeByte(id); + byteBuf.writeVarInt(serializedId); + serializer.write(byteBuf, val); + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/OcclusionClipContext.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/OcclusionClipContext.java new file mode 100644 index 0000000..bfa968f --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/OcclusionClipContext.java @@ -0,0 +1,115 @@ +package com.ticxo.modelengine.v1_20_R1.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.isOpaque() && state.getOcclusionShape(world, pos) == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (tX > 1.0 && tY > 1.0 && tZ > 1.0) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/TrackedEntityImpl.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..4c1cf8c --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/TrackedEntityImpl.java @@ -0,0 +1,286 @@ +package com.ticxo.modelengine.v1_20_R1.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R1.NMSFields; +import com.ticxo.modelengine.v1_20_R1.NMSMethods; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.v1_20_R1.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } + + @Override + public boolean isViewerSetUnchanged() { + if ((!this.mayHaveForced || this.forcedPairing.isEmpty() && this.forcedRemove.isEmpty()) && this.playerPredicate == DEFAULT_PREDICATE) { + if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } else { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/BodyRotationControlWrapper.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..f65f2d0 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_20_R1.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/LookControlWrapper.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..1083f5a --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/LookControlWrapper.java @@ -0,0 +1,143 @@ +package com.ticxo.modelengine.v1_20_R1.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; +import org.spigotmc.ActivationRange; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/MoveControlWrapper.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..f511b3a --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/controller/MoveControlWrapper.java @@ -0,0 +1,247 @@ +package com.ticxo.modelengine.v1_20_R1.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.mount.controller.MountController.MountInput; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R1.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.craftbukkit.v1_20_R1.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + controller.setInput(new MountInput()); + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/hitbox/HitboxEntityImpl.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..9be52bd --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,269 @@ +package com.ticxo.modelengine.v1_20_R1.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_20_R1.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_20_R1.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.v1_20_R1.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public Iterable getArmorSlots() { + return this.armorItems; + } + + public ItemStack getItemBySlot(EquipmentSlot slot) { + return switch (slot.getType()) { + case HAND -> (ItemStack)this.handItems.get(slot.getIndex()); + case ARMOR -> (ItemStack)this.armorItems.get(slot.getIndex()); + default -> throw new IncompatibleClassChangeError(); + }; + } + + public void setItemSlot(EquipmentSlot slot, ItemStack stack) { + this.verifyEquippedItem(stack); + switch (slot.getType()) { + case HAND: + this.onEquipItem(slot, this.handItems.set(slot.getIndex(), stack), stack); + break; + case ARMOR: + this.onEquipItem(slot, this.armorItems.set(slot.getIndex(), stack), stack); + } + } + + public boolean isInvisible() { + return true; + } + + public void push(Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox() { + if (this.subHitbox == null) { + return super.makeBoundingBox(); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurt(DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurt(source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return this.bone.getActiveModel().getModeledEntity().getBase().hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, + entity, + new Vector(0, 0, 0), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + com.ticxo.modelengine.api.nms.entity.EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact( + this, + player.getBukkitEntity(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND + ); + + return switch (result) { + case SUCCESS, SUCCESS_NO_ITEM_USED -> InteractionResult.SUCCESS; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.CONSUME_PARTIAL; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }; + } + } + + public boolean shouldBeSaved() { + return false; + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/hitbox/OBB.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/hitbox/OBB.java new file mode 100644 index 0000000..b028875 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_20_R1.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..34600b4 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_20_R1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..a9b5749 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/GroundNavigationWrapper.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..5390ea9 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..1b656c3 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..594a6f3 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_20_R1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/ModelEngineChannelHandler.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..bd9dfe3 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/ModelEngineChannelHandler.java @@ -0,0 +1,452 @@ +package com.ticxo.modelengine.v1_20_R1.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.mount.controller.MountController.MountInput; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R1.NMSFields; +import com.ticxo.modelengine.v1_20_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R1.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntListIterator; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAddPlayerPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.v1_20_R1.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundAddPlayerPacket.class, this::handleAddPlayer) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost) + .registerPost(ClientboundAddPlayerPacket.class, this::handleAddPlayerPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + + for (Packet p : this.writeInterceptors.acceptPost(result)) { + list.add(p); + } + } + } + + if (!list.isEmpty()) { + Packet var13 = new ClientboundBundlePacket(list); + super.write(ctx, var13, promise); + } + } else { + Packet var14 = this.writeInterceptors.accept(packet); + if (var14 == null) { + return; + } + + Collection post = this.writeInterceptors.acceptPost(var14); + if (post.isEmpty()) { + super.write(ctx, var14, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var14); + + for (Packet p : post) { + list.add(p); + } + + Packet var15 = new ClientboundBundlePacket(list); + super.write(ctx, var15, promise); + } + } + } catch (Throwable var12) { + var12.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private ClientboundAddPlayerPacket handleAddPlayer(ClientboundAddPlayerPacket packet) { + int id = packet.getEntityId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private List handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List handleAddPlayerPost(ClientboundAddPlayerPacket packet) { + return this.handleMount(packet.getPlayerId()); + } + + private List handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + ArrayList list = new ArrayList<>(); + model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT).ifPresent(behaviorRenderer -> { + if (behaviorRenderer instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + CollectionDataTracker ids = mount.getPassengers(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(mount.getMountId()); + buf.writeVarInt(ids.size()); + ids.forEach(buf::writeVarInt); + list.add(new ClientboundSetPassengersPacket(buf)); + } + } + }); + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int size = buf.readVarInt(); + HashSet set = new HashSet<>(size); + + for (int i = 0; i < size; i++) { + int id = buf.readVarInt(); + this.markViewersDirty(id); + if (ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE) { + set.add(id); + } + } + + if (set.size() == size) { + return packet; + } else { + buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(set.size()); + + for (int id : set) { + buf.writeVarInt(id); + } + + return new ClientboundRemoveEntitiesPacket(buf); + } + } + + private > Packet handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int id = buf.readVarInt(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private > Packet handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(packet.id()); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, data); + } else { + EntityUtils.writeDataUnsafe(buf, item.id(), item.serializer(), item.value()); + } + } + + buf.writeByte(255); + packet = new ClientboundSetEntityDataPacket(buf); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int id = buf.readVarInt(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + if (!changed) { + return packet; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(packet.getVehicle()); + buf.writeVarInt(merged.size()); + IntListIterator var16 = merged.iterator(); + + while (var16.hasNext()) { + int idx = (Integer)var16.next(); + buf.writeVarInt(idx); + } + + return new ClientboundSetPassengersPacket(buf); + } + } + } + } + + private ServerboundInteractPacket handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int entityId = buf.readVarInt(); + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, packet) : packet; + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountInput input = controller.getInput(); + if (input == null) { + controller.setInput(new MountInput(inputPacket.getXxa(), inputPacket.getZza(), inputPacket.isJumping(), inputPacket.isShiftKeyDown())); + } else { + input.setSide(inputPacket.getXxa()); + input.setFront(inputPacket.getZza()); + input.setJump(inputPacket.isJumping()); + input.setSneak(inputPacket.isShiftKeyDown()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + return packet; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/NetworkHandlerImpl.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..7551391 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/NetworkHandlerImpl.java @@ -0,0 +1,140 @@ +package com.ticxo.modelengine.v1_20_R1.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R1.NMSFields; +import com.ticxo.modelengine.v1_20_R1.network.utils.Bundler; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundPingPacket; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.v1_20_R1.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/patch/PatchedServerGamePacketListener.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..a0893aa --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,408 @@ +package com.ticxo.modelengine.v1_20_R1.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent.Action; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R1.NMSMethods; +import java.util.Arrays; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.v1_20_R1.CraftServer; +import org.bukkit.craftbukkit.v1_20_R1.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_20_R1.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().serverLevel()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.serverLevel(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + final ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + null + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT_ON, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + position + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT_ON, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + position + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.ATTACK, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, null); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, pos); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent( + craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND, null + ); + } + } + ); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE)) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelected().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + entity.getEntityData().resendPossiblyDesyncedEntity(player); + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem) { + entity.getEntityData().refresh(player); + if (entity instanceof Allay allay) { + connection.send( + new ClientboundSetEquipmentPacket( + entity.getId(), + Arrays.stream(net.minecraft.world.entity.EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.stripMeta(allay.getItemBySlot(slot), true))) + .collect(Collectors.toList()) + ) + ); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.serverLevel()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.serverLevel(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level().clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.isSameItemSameTags(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand, + movingobjectpositionblock.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, org.bukkit.event.block.Action.RIGHT_CLICK_AIR, itemstack, enumhand + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.resyncUsingItem(player); + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent( + CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacket packet, InteractionHand hand, @Nullable Vec3 vector + ) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.isAttack(), + hand == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND, + vector != null ? new Vector(vector.x, vector.y, vector.z) : null + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..17e2448 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,63 @@ +package com.ticxo.modelengine.v1_20_R1.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper extends ServerboundInteractPacket { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, ServerboundInteractPacket original) { + super(NetworkUtils.readData(original)); + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + } + + public void write(FriendlyByteBuf var0) { + this.original.write(var0); + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/BulkEntityDataEncoder.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..e543357 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_20_R1.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/Bundler.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/Bundler.java new file mode 100644 index 0000000..a334cb0 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_20_R1.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.get(this.bundles.size() - 1); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.get(this.bundles.size() - 1); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet p : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(p); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/NetworkUtils.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/NetworkUtils.java new file mode 100644 index 0000000..f18818f --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/NetworkUtils.java @@ -0,0 +1,271 @@ +package com.ticxo.modelengine.v1_20_R1.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler.LODTracker; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_20_R1.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.util.Collection; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static FriendlyByteBuf createByteBuf() { + return new FriendlyByteBuf(Unpooled.buffer()); + } + + public static FriendlyByteBuf createByteBuf(Consumer consumer) { + FriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static FriendlyByteBuf readData(Packet packet) { + FriendlyByteBuf buf = createByteBuf(); + packet.write(buf); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + FriendlyByteBuf buf = createByteBuf(); + buf.writeVarInt(id); + buf.writeDouble(pos.x); + buf.writeDouble(pos.y - 0.375); + buf.writeDouble(pos.z); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + ClientboundTeleportEntityPacket tpHigher = new ClientboundTeleportEntityPacket(buf); + buf = createByteBuf(); + buf.writeVarInt(id); + buf.writeDouble(pos.x); + buf.writeDouble(pos.y - 0.5); + buf.writeDouble(pos.z); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + ClientboundTeleportEntityPacket tpLower = new ClientboundTeleportEntityPacket(buf); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Packets.PacketSupplier lodWrapper(ModeledEntity modeledEntity, BiFunction> packetFunction) { + return uuid -> { + LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/PacketInterceptor.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..a36907e --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/PacketInterceptor.java @@ -0,0 +1,83 @@ +package com.ticxo.modelengine.v1_20_R1.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor { + private final Map, PacketInterceptor.Modifier> registry = Maps.newConcurrentMap(); + private final Map, PacketInterceptor.Listener> postRegistry = Maps.newConcurrentMap(); + + public PacketInterceptor register(Class clazz, Function function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public PacketInterceptor registerPost(Class clazz, Function> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor.Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor.Listener listener = this.postRegistry.get(original.getClass()); + return (Collection)(listener != null ? listener.listen(original) : List.of()); + } + } + + static class Listener { + private final Class clazz; + private final Function> function; + + public Collection listen(Packet original) { + try { + Collection collection = this.function.apply(this.clazz.cast(original)); + return (Collection)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(Class clazz, Function> function) { + this.clazz = clazz; + this.function = function; + } + } + + static class Modifier { + private final Class clazz; + private final Function function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(Class clazz, Function function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/Packets.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/Packets.java new file mode 100644 index 0000000..4628d24 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_20_R1.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/HeldItemParser.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..3c5e8f2 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/HeldItemParser.java @@ -0,0 +1,198 @@ +package com.ticxo.modelengine.v1_20_R1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer.Item; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.v1_20_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.Packets; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_20_R1.inventory.CraftItemStack; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size()); + destroy.forEach((s, item) -> buf.writeVarInt(item.getId())); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Map items = renderer.getRendered(); + buf.writeVarInt(1 + items.size()); + buf.writeVarInt(renderer.getId()); + items.forEach((s, item) -> buf.writeVarInt(item.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)16); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + if (spawn) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, 1); + EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, this.viewRange); + } else if (renderer.isTransformDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + renderer.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), spawn); + renderer.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 21, EntityDataSerializers.INT, color), spawn); + renderer.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 10, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getRotation().ifDirty(quaternionf -> EntityUtils.writeData(buf, 12, EntityDataSerializers.QUATERNION, quaternionf), spawn); + renderer.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), spawn); + renderer.getDisplay() + .ifDirty(display -> EntityUtils.writeData(buf, 23, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(location.getX(), location.getY(), location.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + buf.writeDouble(location.getX()); + buf.writeDouble(location.getY()); + buf.writeDouble(location.getZ()); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + return new ClientboundTeleportEntityPacket(buf); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + CollectionDataTracker set = renderer.getPassengers(); + buf.writeVarInt(set.size()); + set.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/LeashParser.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/LeashParser.java new file mode 100644 index 0000000..03af0ad --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/LeashParser.java @@ -0,0 +1,176 @@ +package com.ticxo.modelengine.v1_20_R1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer.Leash; +import com.ticxo.modelengine.v1_20_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Map leashes = renderer.getRendered(); + buf.writeVarInt(leashes.size()); + leashes.forEach((s, leash) -> buf.writeVarInt(leash.getLeashId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos); + } + + private ClientboundAddEntityPacket leashSpawn(Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.SLIME, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getLeashId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetEntityDataPacket leashData(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getLeashId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, 0); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket mount(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(buf); + } + + private Object move(Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos); + } + } + + private ClientboundSetEntityLinkPacket link(Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeInt(renderer.getLeashId()); + buf.writeInt(renderer.getConnected().get()); + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(buf); + } + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/MountParser.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/MountParser.java new file mode 100644 index 0000000..9b5ce8e --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/MountParser.java @@ -0,0 +1,244 @@ +package com.ticxo.modelengine.v1_20_R1.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer.Mount; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.AttributeSnapshot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, mount) -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getMountId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection mounts = renderer.getRendered().values(); + buf.writeVarInt(mounts.size() * 2); + mounts.forEach(mount -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getMountId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(Mount renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket mountSpawn(Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)16); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket pivotMount(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getMountId()); + return new ClientboundSetPassengersPacket(buf); + } + + private ClientboundSetPassengersPacket mount(Mount renderer) { + CollectionDataTracker ids = renderer.getPassengers(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + buf.writeVarInt(ids.size()); + ids.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Packets.PacketSupplier pivotMove(Mount renderer) { + return NetworkUtils.createPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(Mount renderer) { + FriendlyByteBuf rot = NetworkUtils.createByteBuf(); + rot.writeVarInt(renderer.getMountId()); + rot.writeByte(renderer.getYaw().get()); + rot.writeByte(0); + rot.writeBoolean(false); + return Rot.read(rot); + } + + private ClientboundSetEntityDataPacket mountHealth(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, renderer.getHealth().get()); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection attributes = Lists.newArrayList(); + attributes.add(new AttributeSnapshot(Attributes.MAX_HEALTH, renderer.getMaxHealth().get().floatValue(), Lists.newArrayList())); + buf.writeVarInt(renderer.getMountId()); + buf.writeCollection(attributes, (buf2, attribute) -> { + buf2.writeResourceLocation(BuiltInRegistries.ATTRIBUTE.getKey(attribute.getAttribute())); + buf2.writeDouble(attribute.getBase()); + buf2.writeCollection(attribute.getModifiers(), (buf3, modifier) -> { + buf3.writeUUID(modifier.getId()); + buf3.writeDouble(modifier.getAmount()); + buf3.writeByte(modifier.getOperation().toValue()); + }); + }); + return new ClientboundUpdateAttributesPacket(buf); + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/NameTagParser.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..7765d67 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/NameTagParser.java @@ -0,0 +1,196 @@ +package com.ticxo.modelengine.v1_20_R1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer.NameTag; +import com.ticxo.modelengine.v1_20_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Component.Serializer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, mount) -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getTagId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection nameTags = renderer.getRendered().values(); + buf.writeVarInt(nameTags.size() * 2); + nameTags.forEach(nameTag -> { + buf.writeVarInt(nameTag.getPivotId()); + buf.writeVarInt(nameTag.getTagId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + if (spawn) { + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + } + + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getTagId()); + renderer.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), spawn); + renderer.getTranslate().ifDirty(vector3f -> EntityUtils.writeData(buf, 10, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getTextOpacity().ifDirty(flag -> EntityUtils.writeData(buf, 26, EntityDataSerializers.BYTE, flag), spawn); + renderer.getLineWidth().ifDirty(flag -> EntityUtils.writeData(buf, 24, EntityDataSerializers.INT, flag), spawn); + renderer.getBackgroundColor().ifDirty(flag -> EntityUtils.writeData(buf, 25, EntityDataSerializers.INT, flag), spawn); + renderer.getStyle().ifDirty(flags -> EntityUtils.writeData(buf, 27, EntityDataSerializers.BYTE, flags), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new IncompatibleClassChangeError(); + }; + EntityUtils.writeData(buf, 14, EntityDataSerializers.BYTE, value); + }, spawn); + renderer.getJsonString().ifDirty(jsonString -> { + if (jsonString == null) { + EntityUtils.writeData(buf, 23, EntityDataSerializers.COMPONENT, Component.empty()); + } else { + EntityUtils.writeData(buf, 23, EntityDataSerializers.COMPONENT, Serializer.fromJson(jsonString)); + } + }, spawn); + renderer.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 15, EntityDataSerializers.INT, val), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object pivotMove(NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTag renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getTagId()); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/SegmentParser.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..fdb3949 --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/SegmentParser.java @@ -0,0 +1,220 @@ +package com.ticxo.modelengine.v1_20_R1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer.Pivot; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer.SegmentDisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayBone.BoneData; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_20_R1.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentDisplayBone bone : pivot.getRendered().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + HashSet destroy = new HashSet<>(); + + for (Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeCollection(destroy, FriendlyByteBuf::writeVarInt); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket pivotMount(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + buf.writeCollection(pivot.getPassengers(), FriendlyByteBuf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Object pivotTeleport(Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(Pivot pivot, BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + if (force) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } else if (bone.isTransformDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, flag ? 0 : 1), force); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), force); + bone.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 21, EntityDataSerializers.INT, color), force); + bone.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 15, EntityDataSerializers.INT, val), force); + bone.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 10, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> EntityUtils.writeData(buf, 12, EntityDataSerializers.QUATERNION, quaternionf), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> EntityUtils.writeData(buf, 14, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), force); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), force); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 23, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), force); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + return new ClientboundSetEntityDataPacket(buf); + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/SubHitboxParser.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..6d2c80c --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/behavior/SubHitboxParser.java @@ -0,0 +1,163 @@ +package com.ticxo.modelengine.v1_20_R1.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer.SubHitbox; +import com.ticxo.modelengine.v1_20_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, subHitboxx) -> { + buf.writeVarInt(subHitboxx.getPivotId()); + buf.writeVarInt(subHitboxx.getHitboxId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection subHitboxes = renderer.getRendered().values(); + buf.writeVarInt(subHitboxes.size() * 2); + subHitboxes.forEach(subHitbox -> { + buf.writeVarInt(subHitbox.getPivotId()); + buf.writeVarInt(subHitbox.getHitboxId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitbox renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private Object pivotMove(SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitbox renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getHitboxId()); + return new ClientboundSetPassengersPacket(buf); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getHitboxId()); + renderer.getWidth().ifDirty(width -> EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, width), spawn); + renderer.getHeight().ifDirty(height -> EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, height), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/model/DisplayParser.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/model/DisplayParser.java new file mode 100644 index 0000000..ac7ee1d --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/model/DisplayParser.java @@ -0,0 +1,732 @@ +package com.ticxo.modelengine.v1_20_R1.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler.LODTracker; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.model.render.DisplayBone.BoneData; +import com.ticxo.modelengine.api.model.render.DisplayRenderer.Hitbox; +import com.ticxo.modelengine.api.model.render.DisplayRenderer.Pivot; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_20_R1.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static Constructor CUSTOM_PAYLOAD_CONSTRUCTOR; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size()); + destroy.forEach(buf::writeVarInt); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitboxDestroy.size()); + hitboxDestroy.forEach(buf::writeVarInt); + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)u -> this.displayData(u, null, boneData, false, transformOnly)); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(FriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CONSTRUCTOR == null) { + CUSTOM_PAYLOAD_CONSTRUCTOR = ClientboundCustomPayloadPacket.class.getDeclaredConstructor(FriendlyByteBuf.class); + CUSTOM_PAYLOAD_CONSTRUCTOR.setAccessible(true); + } + + return (Packet)CUSTOM_PAYLOAD_CONSTRUCTOR.newInstance(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData(BulkEntityDataEncoder encoder, UUID uuid, @Nullable LODTracker tracker, BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(Pivot pivot) { + return pivot.isOverridden() ? null : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Pivot pivot) { + if (pivot.isOverridden()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundSetPassengersPacket pivotMount(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + buf.writeVarInt(pivot.getPassengers().size()); + pivot.getPassengers().forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Object pivotTeleport(Pivot pivot) { + return !pivot.getPosition().isDirty() ? null : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + + private ClientboundAddEntityPacket displaySpawn(Pivot pivot, BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, @Nullable LODTracker tracker, BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + if (!force && update != 0) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + EntityUtils.writeData(buf, 21, EntityDataSerializers.INT, color); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + EntityUtils.writeData(buf, 15, EntityDataSerializers.INT, val); + } + }, force); + bone.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 10, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> EntityUtils.writeData(buf, 12, EntityDataSerializers.QUATERNION, quaternionf), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + EntityUtils.writeData(buf, 14, EntityDataSerializers.BYTE, (byte)billboard.ordinal()); + } + }, force); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), force); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), force); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 23, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), force); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetEntityDataPacket displayVisibleData(BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))); + bone.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 21, EntityDataSerializers.INT, color)); + bone.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 15, EntityDataSerializers.INT, val)); + bone.getBillboard().ifDirty(billboard -> EntityUtils.writeData(buf, 14, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 23, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundAddEntityPacket hitboxSpawn(Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getHitboxId()); + hitbox.getWidth().ifDirty(val -> EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, val), spawn); + hitbox.getHeight().ifDirty(val -> EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, val), spawn); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getShadowId()); + hitbox.getShadowRadius().ifDirty(val -> EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, val), spawn); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(14, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(15, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(10, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(16, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getPivotId()); + buf.writeVarInt(passengers.size()); + passengers.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + } +} diff --git a/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/vfx/VFXDisplayParser.java b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..5960cfd --- /dev/null +++ b/nms/v1_20_R1/src/main/java/com/ticxo/modelengine/v1_20_R1/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,138 @@ +package com.ticxo.modelengine.v1_20_R1.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer.VFXModel; +import com.ticxo.modelengine.v1_20_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R1.network.utils.Packets; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_20_R1.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(2); + buf.writeVarInt(vfx.getPivotId()); + buf.writeVarInt(vfx.getModelId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXModel vfx) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getModelId()); + if (spawn) { + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, 1); + EntityUtils.writeData(buf, 16, EntityDataSerializers.FLOAT, 4096.0F); + EntityUtils.writeData(buf, 23, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal()); + } else if (vfx.isModelDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + vfx.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 10, EntityDataSerializers.VECTOR3, vector3f), spawn); + vfx.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> EntityUtils.writeData(buf, 12, EntityDataSerializers.QUATERNION, quaternionf), spawn); + vfx.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 22, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), spawn); + vfx.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 15, EntityDataSerializers.INT, val), spawn); + buf.writeByte(255); + vfx.clearModelDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object teleport(VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXModel vfx) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(vfx.getModelId()); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSFields.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSFields.java new file mode 100644 index 0000000..87814f8 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSFields.java @@ -0,0 +1,58 @@ +package com.ticxo.modelengine.v1_20_R2; + +import com.ticxo.modelengine.api.utils.ReflectionUtils.ReflectionEnum; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionEnum { + ENTITY_dimensions(Entity.class, "bh", "dimensions"), + ENTITY_eyeHeight(Entity.class, "bi", "eyeHeight"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "ca", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "bj", "jumping"), + MOB_lookControl(Mob.class, "bK", "lookControl"), + MOB_moveControl(Mob.class, "bL", "moveControl"), + MOB_navigation(Mob.class, "bN", "navigation"), + MOB_goalSelector(Mob.class, "bO", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "bU", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "E", "clientIsFloating"), + SERVER_COMMON_PACKET_LISTENER_IMPL_connection(ServerCommonPacketListenerImpl.class, "c", "connection"), + MOVE_CONTROL_operation(MoveControl.class, "k", "operation"), + TRACKED_ENTITY_serverEntity(TrackedEntity.class, "b", "serverEntity"), + TRACKED_ENTITY_range(TrackedEntity.class, "d", "range"), + LEVEL_threadSafeRandom(Level.class, "f", "threadSafeRandom"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "a", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "a", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(Class target, String obfuscated, String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSHandler_v1_20_R2.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSHandler_v1_20_R2.java new file mode 100644 index 0000000..ac47ac8 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSHandler_v1_20_R2.java @@ -0,0 +1,182 @@ +package com.ticxo.modelengine.v1_20_R2; + +import com.mojang.math.MatrixUtil; +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.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_20_R2.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_20_R2.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R2.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_20_R2.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_20_R2.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_20_R2.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_20_R2.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_20_R2.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_20_R2.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.entity.Entity; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_20_R2 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + FriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, new ClientboundSetPassengersPacket(byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(mountId); + buf.writeVarInt(passengerIds.size()); + passengerIds.forEach(buf::writeVarInt); + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(buf); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSMethods.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSMethods.java new file mode 100644 index 0000000..d8732ae --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/NMSMethods.java @@ -0,0 +1,48 @@ +package com.ticxo.modelengine.v1_20_R2; + +import com.ticxo.modelengine.api.utils.ReflectionUtils.MethodEnum; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "d", "getInstrument", ItemStack.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityHandlerImpl.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..7402dba --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityHandlerImpl.java @@ -0,0 +1,714 @@ +package com.ticxo.modelengine.v1_20_R2.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.nms.entity.EntityHandler.BoxRelToCam; +import com.ticxo.modelengine.api.nms.entity.EntityHandler.InteractionResult; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_20_R2.NMSFields; +import com.ticxo.modelengine.v1_20_R2.NMSMethods; +import com.ticxo.modelengine.v1_20_R2.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_20_R2.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_20_R2.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_20_R2.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_20_R2.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_20_R2.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_20_R2.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_20_R2.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_20_R2.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_20_R2.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.minecraft.core.Holder; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.UseAnim; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.v1_20_R2.CraftWorld; +import org.bukkit.craftbukkit.v1_20_R2.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_20_R2.inventory.CraftItemStack; +import org.bukkit.craftbukkit.v1_20_R2.util.CraftLocation; +import org.bukkit.craftbukkit.v1_20_R2.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions((float)hitbox.getMaxWidth(), (float)hitbox.getHeight(), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + EntityUtils.nms(entity).setMaxUpStep((float)height); + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityType.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y + nmsEntity.getMyRidingOffset(this.dummyArmorStand); + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(entity.getEntityId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, data); + buf.writeByte(255); + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket(buf); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + if (oldNav instanceof WallClimberNavigation wallClimberNavigation) { + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + } else if (oldNav instanceof GroundPathNavigation groundPathNavigation) { + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + } else if (oldNav instanceof FlyingPathNavigation flyingPathNavigation) { + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + } else if (oldNav instanceof WaterBoundPathNavigation) { + newNav = new WaterBoundNavigationWrapper(mob); + } else { + if (!(oldNav instanceof AmphibiousPathNavigation amphibiousPathNavigation)) { + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var10) { + var10.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + ServerLevel level = ((CraftWorld)location.getWorld()).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + return EntityUtils.nms(entity).hurt(damageSource, amount); + } else { + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + } + + @Override + public InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case SUCCESS -> InteractionResult.SUCCESS; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.CONSUME_PARTIAL; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + default -> throw new IncompatibleClassChangeError(); + }; + } else { + return InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + FriendlyByteBuf pivotDataBuf = NetworkUtils.createByteBuf(); + pivotDataBuf.writeVarInt(DynamicHitbox.getPivotId()); + EntityUtils.writeData(pivotDataBuf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(pivotDataBuf, 8, EntityDataSerializers.FLOAT, 0.0F); + pivotDataBuf.writeByte(255); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket(pivotDataBuf); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + FriendlyByteBuf hitboxDataBuf = NetworkUtils.createByteBuf(); + hitboxDataBuf.writeVarInt(DynamicHitbox.getHitboxId()); + EntityUtils.writeData(hitboxDataBuf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(hitboxDataBuf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(hitboxDataBuf, 16, EntityDataSerializers.INT, 2); + hitboxDataBuf.writeByte(255); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(hitboxDataBuf); + FriendlyByteBuf mountBuf = NetworkUtils.createByteBuf(); + mountBuf.writeVarInt(DynamicHitbox.getPivotId()); + mountBuf.writeVarInt(1); + mountBuf.writeVarInt(DynamicHitbox.getHitboxId()); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket(mountBuf); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0 + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != UseAnim.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(player.getEntityId()); + EntityUtils.writeData(buf, 8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3)); + buf.writeByte(255); + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket(buf); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call(instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = level.getChunkSource().chunkMap.entityMap; + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = lvl.getChunkSource().chunkMap.entityMap; + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3D(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + BoxRelToCam relX = BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + BoxRelToCam relY = BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + BoxRelToCam relZ = BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == BoxRelToCam.INSIDE && relY == BoxRelToCam.INSIDE && relZ == BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.REDSTONE, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityMetadataID.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityMetadataID.java new file mode 100644 index 0000000..0dd3c26 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityMetadataID.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.v1_20_R2.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityUtils.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityUtils.java new file mode 100644 index 0000000..9808062 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/EntityUtils.java @@ -0,0 +1,27 @@ +package com.ticxo.modelengine.v1_20_R2.entity; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.syncher.EntityDataSerializer; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.v1_20_R2.entity.CraftEntity; + +public class EntityUtils { + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } + + public static void writeData(FriendlyByteBuf byteBuf, int id, EntityDataSerializer serializer, T val) { + int serializedId = EntityDataSerializers.getSerializedId(serializer); + byteBuf.writeByte(id); + byteBuf.writeVarInt(serializedId); + serializer.write(byteBuf, val); + } + + public static void writeDataUnsafe(FriendlyByteBuf byteBuf, int id, EntityDataSerializer serializer, Object val) { + int serializedId = EntityDataSerializers.getSerializedId(serializer); + byteBuf.writeByte(id); + byteBuf.writeVarInt(serializedId); + serializer.write(byteBuf, val); + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/OcclusionClipContext.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/OcclusionClipContext.java new file mode 100644 index 0000000..bda3b82 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/OcclusionClipContext.java @@ -0,0 +1,115 @@ +package com.ticxo.modelengine.v1_20_R2.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.isOpaque() && state.getOcclusionShape(world, pos) == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (tX > 1.0 && tY > 1.0 && tZ > 1.0) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/TrackedEntityImpl.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..38cda65 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/TrackedEntityImpl.java @@ -0,0 +1,286 @@ +package com.ticxo.modelengine.v1_20_R2.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R2.NMSFields; +import com.ticxo.modelengine.v1_20_R2.NMSMethods; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.v1_20_R2.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } + + @Override + public boolean isViewerSetUnchanged() { + if ((!this.mayHaveForced || this.forcedPairing.isEmpty() && this.forcedRemove.isEmpty()) && this.playerPredicate == DEFAULT_PREDICATE) { + if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } else { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/BodyRotationControlWrapper.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..f34cf84 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_20_R2.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/LookControlWrapper.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..1520697 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/LookControlWrapper.java @@ -0,0 +1,143 @@ +package com.ticxo.modelengine.v1_20_R2.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; +import org.spigotmc.ActivationRange; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/MoveControlWrapper.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..ba971d7 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/controller/MoveControlWrapper.java @@ -0,0 +1,247 @@ +package com.ticxo.modelengine.v1_20_R2.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.mount.controller.MountController.MountInput; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R2.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.craftbukkit.v1_20_R2.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + controller.setInput(new MountInput()); + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/hitbox/HitboxEntityImpl.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..8b1c6b8 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,269 @@ +package com.ticxo.modelengine.v1_20_R2.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_20_R2.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_20_R2.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.v1_20_R2.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public Iterable getArmorSlots() { + return this.armorItems; + } + + public ItemStack getItemBySlot(EquipmentSlot slot) { + return switch (slot.getType()) { + case HAND -> (ItemStack)this.handItems.get(slot.getIndex()); + case ARMOR -> (ItemStack)this.armorItems.get(slot.getIndex()); + default -> throw new IncompatibleClassChangeError(); + }; + } + + public void setItemSlot(EquipmentSlot slot, ItemStack stack) { + this.verifyEquippedItem(stack); + switch (slot.getType()) { + case HAND: + this.onEquipItem(slot, this.handItems.set(slot.getIndex(), stack), stack); + break; + case ARMOR: + this.onEquipItem(slot, this.armorItems.set(slot.getIndex(), stack), stack); + } + } + + public boolean isInvisible() { + return true; + } + + public void push(Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox() { + if (this.subHitbox == null) { + return super.makeBoundingBox(); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurt(DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurt(source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return this.bone.getActiveModel().getModeledEntity().getBase().hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, + entity, + new Vector(0, 0, 0), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + com.ticxo.modelengine.api.nms.entity.EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact( + this, + player.getBukkitEntity(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND + ); + + return switch (result) { + case SUCCESS, SUCCESS_NO_ITEM_USED -> InteractionResult.SUCCESS; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.CONSUME_PARTIAL; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }; + } + } + + public boolean shouldBeSaved() { + return false; + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/hitbox/OBB.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/hitbox/OBB.java new file mode 100644 index 0000000..541468d --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_20_R2.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..b56d455 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_20_R2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..7033620 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/GroundNavigationWrapper.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..e150333 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..f13fff6 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..69f908e --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_20_R2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/ModelEngineChannelHandler.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..f1332a5 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/ModelEngineChannelHandler.java @@ -0,0 +1,439 @@ +package com.ticxo.modelengine.v1_20_R2.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.mount.controller.MountController.MountInput; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R2.NMSFields; +import com.ticxo.modelengine.v1_20_R2.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntListIterator; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.v1_20_R2.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + + for (Packet p : this.writeInterceptors.acceptPost(result)) { + list.add(p); + } + } + } + + if (!list.isEmpty()) { + Packet var13 = new ClientboundBundlePacket(list); + super.write(ctx, var13, promise); + } + } else { + Packet var14 = this.writeInterceptors.accept(packet); + if (var14 == null) { + return; + } + + Collection post = this.writeInterceptors.acceptPost(var14); + if (post.isEmpty()) { + super.write(ctx, var14, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var14); + + for (Packet p : post) { + list.add(p); + } + + Packet var15 = new ClientboundBundlePacket(list); + super.write(ctx, var15, promise); + } + } + } catch (Throwable var12) { + var12.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + ArrayList list = new ArrayList<>(); + model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT).ifPresent(behaviorRenderer -> { + if (behaviorRenderer instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + CollectionDataTracker ids = mount.getPassengers(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(mount.getMountId()); + buf.writeVarInt(ids.size()); + ids.forEach(buf::writeVarInt); + list.add(new ClientboundSetPassengersPacket(buf)); + } + } + }); + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int size = buf.readVarInt(); + HashSet set = new HashSet<>(size); + + for (int i = 0; i < size; i++) { + int id = buf.readVarInt(); + this.markViewersDirty(id); + if (ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE) { + set.add(id); + } + } + + if (set.size() == size) { + return packet; + } else { + buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(set.size()); + + for (int id : set) { + buf.writeVarInt(id); + } + + return new ClientboundRemoveEntitiesPacket(buf); + } + } + + private > Packet handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int id = buf.readVarInt(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private > Packet handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(packet.id()); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + buf.writeByte(255); + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int id = buf.readVarInt(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + if (!changed) { + return packet; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(packet.getVehicle()); + buf.writeVarInt(merged.size()); + IntListIterator var16 = merged.iterator(); + + while (var16.hasNext()) { + int idx = (Integer)var16.next(); + buf.writeVarInt(idx); + } + + return new ClientboundSetPassengersPacket(buf); + } + } + } + } + + private ServerboundInteractPacket handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int entityId = buf.readVarInt(); + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, packet) : packet; + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountInput input = controller.getInput(); + if (input == null) { + controller.setInput(new MountInput(inputPacket.getXxa(), inputPacket.getZza(), inputPacket.isJumping(), inputPacket.isShiftKeyDown())); + } else { + input.setSide(inputPacket.getXxa()); + input.setFront(inputPacket.getZza()); + input.setJump(inputPacket.isJumping()); + input.setSneak(inputPacket.isShiftKeyDown()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + return packet; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/NetworkHandlerImpl.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..6c619b0 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/NetworkHandlerImpl.java @@ -0,0 +1,140 @@ +package com.ticxo.modelengine.v1_20_R2.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R2.NMSFields; +import com.ticxo.modelengine.v1_20_R2.network.utils.Bundler; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.v1_20_R2.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/patch/PatchedServerGamePacketListener.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..0e75e1d --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,408 @@ +package com.ticxo.modelengine.v1_20_R2.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent.Action; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R2.NMSMethods; +import java.util.Arrays; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.v1_20_R2.CraftServer; +import org.bukkit.craftbukkit.v1_20_R2.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_20_R2.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().serverLevel()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.serverLevel(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + final ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + null + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT_ON, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + position + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT_ON, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + position + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.ATTACK, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, null); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, pos); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent( + craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND, null + ); + } + } + ); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE)) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelected().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + entity.getEntityData().resendPossiblyDesyncedEntity(player); + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem) { + entity.getEntityData().refresh(player); + if (entity instanceof Allay allay) { + connection.send( + new ClientboundSetEquipmentPacket( + entity.getId(), + Arrays.stream(net.minecraft.world.entity.EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.stripMeta(allay.getItemBySlot(slot), true))) + .collect(Collectors.toList()) + ) + ); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.serverLevel()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.serverLevel(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level().clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.isSameItemSameTags(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand, + movingobjectpositionblock.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, org.bukkit.event.block.Action.RIGHT_CLICK_AIR, itemstack, enumhand + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.resyncUsingItem(player); + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent( + CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacket packet, InteractionHand hand, @Nullable Vec3 vector + ) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.isAttack(), + hand == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND, + vector != null ? new Vector(vector.x, vector.y, vector.z) : null + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..dff4073 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,63 @@ +package com.ticxo.modelengine.v1_20_R2.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper extends ServerboundInteractPacket { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, ServerboundInteractPacket original) { + super(NetworkUtils.readData(original)); + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + } + + public void write(FriendlyByteBuf var0) { + this.original.write(var0); + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/BulkEntityDataEncoder.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..0614521 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_20_R2.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/Bundler.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/Bundler.java new file mode 100644 index 0000000..79a32b7 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_20_R2.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.get(this.bundles.size() - 1); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.get(this.bundles.size() - 1); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet p : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(p); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/NetworkUtils.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/NetworkUtils.java new file mode 100644 index 0000000..bad9326 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/NetworkUtils.java @@ -0,0 +1,271 @@ +package com.ticxo.modelengine.v1_20_R2.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler.LODTracker; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_20_R2.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.util.Collection; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static FriendlyByteBuf createByteBuf() { + return new FriendlyByteBuf(Unpooled.buffer()); + } + + public static FriendlyByteBuf createByteBuf(Consumer consumer) { + FriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static FriendlyByteBuf readData(Packet packet) { + FriendlyByteBuf buf = createByteBuf(); + packet.write(buf); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + FriendlyByteBuf buf = createByteBuf(); + buf.writeVarInt(id); + buf.writeDouble(pos.x); + buf.writeDouble(pos.y - 0.375); + buf.writeDouble(pos.z); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + ClientboundTeleportEntityPacket tpHigher = new ClientboundTeleportEntityPacket(buf); + buf = createByteBuf(); + buf.writeVarInt(id); + buf.writeDouble(pos.x); + buf.writeDouble(pos.y - 0.5); + buf.writeDouble(pos.z); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + ClientboundTeleportEntityPacket tpLower = new ClientboundTeleportEntityPacket(buf); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Packets.PacketSupplier lodWrapper(ModeledEntity modeledEntity, BiFunction> packetFunction) { + return uuid -> { + LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/PacketInterceptor.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..c137293 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/PacketInterceptor.java @@ -0,0 +1,83 @@ +package com.ticxo.modelengine.v1_20_R2.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor { + private final Map, PacketInterceptor.Modifier> registry = Maps.newConcurrentMap(); + private final Map, PacketInterceptor.Listener> postRegistry = Maps.newConcurrentMap(); + + public PacketInterceptor register(Class clazz, Function function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public PacketInterceptor registerPost(Class clazz, Function> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor.Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor.Listener listener = this.postRegistry.get(original.getClass()); + return (Collection)(listener != null ? listener.listen(original) : List.of()); + } + } + + static class Listener { + private final Class clazz; + private final Function> function; + + public Collection listen(Packet original) { + try { + Collection collection = this.function.apply(this.clazz.cast(original)); + return (Collection)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(Class clazz, Function> function) { + this.clazz = clazz; + this.function = function; + } + } + + static class Modifier { + private final Class clazz; + private final Function function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(Class clazz, Function function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/Packets.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/Packets.java new file mode 100644 index 0000000..61bf32a --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_20_R2.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/HeldItemParser.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..e9eb5e5 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/HeldItemParser.java @@ -0,0 +1,198 @@ +package com.ticxo.modelengine.v1_20_R2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer.Item; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.v1_20_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.Packets; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_20_R2.inventory.CraftItemStack; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size()); + destroy.forEach((s, item) -> buf.writeVarInt(item.getId())); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Map items = renderer.getRendered(); + buf.writeVarInt(1 + items.size()); + buf.writeVarInt(renderer.getId()); + items.forEach((s, item) -> buf.writeVarInt(item.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)16); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + if (spawn) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, 1); + EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, this.viewRange); + } else if (renderer.isTransformDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + renderer.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), spawn); + renderer.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 22, EntityDataSerializers.INT, color), spawn); + renderer.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 12, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getRotation().ifDirty(quaternionf -> EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf), spawn); + renderer.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), spawn); + renderer.getDisplay() + .ifDirty(display -> EntityUtils.writeData(buf, 24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(location.getX(), location.getY(), location.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + buf.writeDouble(location.getX()); + buf.writeDouble(location.getY()); + buf.writeDouble(location.getZ()); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + return new ClientboundTeleportEntityPacket(buf); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + CollectionDataTracker set = renderer.getPassengers(); + buf.writeVarInt(set.size()); + set.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/LeashParser.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/LeashParser.java new file mode 100644 index 0000000..7ab043d --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/LeashParser.java @@ -0,0 +1,176 @@ +package com.ticxo.modelengine.v1_20_R2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer.Leash; +import com.ticxo.modelengine.v1_20_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Map leashes = renderer.getRendered(); + buf.writeVarInt(leashes.size()); + leashes.forEach((s, leash) -> buf.writeVarInt(leash.getLeashId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos); + } + + private ClientboundAddEntityPacket leashSpawn(Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.SLIME, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getLeashId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetEntityDataPacket leashData(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getLeashId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, 0); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket mount(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(buf); + } + + private Object move(Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos); + } + } + + private ClientboundSetEntityLinkPacket link(Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeInt(renderer.getLeashId()); + buf.writeInt(renderer.getConnected().get()); + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(buf); + } + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/MountParser.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/MountParser.java new file mode 100644 index 0000000..48c366f --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/MountParser.java @@ -0,0 +1,244 @@ +package com.ticxo.modelengine.v1_20_R2.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer.Mount; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.AttributeSnapshot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, mount) -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getMountId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection mounts = renderer.getRendered().values(); + buf.writeVarInt(mounts.size() * 2); + mounts.forEach(mount -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getMountId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(Mount renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket mountSpawn(Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)16); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket pivotMount(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getMountId()); + return new ClientboundSetPassengersPacket(buf); + } + + private ClientboundSetPassengersPacket mount(Mount renderer) { + CollectionDataTracker ids = renderer.getPassengers(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + buf.writeVarInt(ids.size()); + ids.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Packets.PacketSupplier pivotMove(Mount renderer) { + return NetworkUtils.createPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(Mount renderer) { + FriendlyByteBuf rot = NetworkUtils.createByteBuf(); + rot.writeVarInt(renderer.getMountId()); + rot.writeByte(renderer.getYaw().get()); + rot.writeByte(0); + rot.writeBoolean(false); + return Rot.read(rot); + } + + private ClientboundSetEntityDataPacket mountHealth(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, renderer.getHealth().get()); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection attributes = Lists.newArrayList(); + attributes.add(new AttributeSnapshot(Attributes.MAX_HEALTH, renderer.getMaxHealth().get().floatValue(), Lists.newArrayList())); + buf.writeVarInt(renderer.getMountId()); + buf.writeCollection(attributes, (buf2, attribute) -> { + buf2.writeResourceLocation(BuiltInRegistries.ATTRIBUTE.getKey(attribute.getAttribute())); + buf2.writeDouble(attribute.getBase()); + buf2.writeCollection(attribute.getModifiers(), (buf3, modifier) -> { + buf3.writeUUID(modifier.getId()); + buf3.writeDouble(modifier.getAmount()); + buf3.writeByte(modifier.getOperation().toValue()); + }); + }); + return new ClientboundUpdateAttributesPacket(buf); + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/NameTagParser.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..dd10157 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/NameTagParser.java @@ -0,0 +1,196 @@ +package com.ticxo.modelengine.v1_20_R2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer.NameTag; +import com.ticxo.modelengine.v1_20_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Component.Serializer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, mount) -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getTagId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection nameTags = renderer.getRendered().values(); + buf.writeVarInt(nameTags.size() * 2); + nameTags.forEach(nameTag -> { + buf.writeVarInt(nameTag.getPivotId()); + buf.writeVarInt(nameTag.getTagId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + if (spawn) { + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + } + + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getTagId()); + renderer.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), spawn); + renderer.getTranslate().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 12, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getTextOpacity().ifDirty(flag -> EntityUtils.writeData(buf, 26, EntityDataSerializers.BYTE, flag), spawn); + renderer.getBackgroundColor().ifDirty(flag -> EntityUtils.writeData(buf, 25, EntityDataSerializers.INT, flag), spawn); + renderer.getLineWidth().ifDirty(flag -> EntityUtils.writeData(buf, 24, EntityDataSerializers.INT, flag), spawn); + renderer.getStyle().ifDirty(flags -> EntityUtils.writeData(buf, 27, EntityDataSerializers.BYTE, flags), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new IncompatibleClassChangeError(); + }; + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, value); + }, spawn); + renderer.getJsonString().ifDirty(jsonString -> { + if (jsonString == null) { + EntityUtils.writeData(buf, 23, EntityDataSerializers.COMPONENT, Component.empty()); + } else { + EntityUtils.writeData(buf, 23, EntityDataSerializers.COMPONENT, Serializer.fromJson(jsonString)); + } + }, spawn); + renderer.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, val), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object pivotMove(NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTag renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getTagId()); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/SegmentParser.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..0850e3c --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/SegmentParser.java @@ -0,0 +1,220 @@ +package com.ticxo.modelengine.v1_20_R2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer.Pivot; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer.SegmentDisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayBone.BoneData; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_20_R2.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentDisplayBone bone : pivot.getRendered().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + HashSet destroy = new HashSet<>(); + + for (Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeCollection(destroy, FriendlyByteBuf::writeVarInt); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket pivotMount(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + buf.writeCollection(pivot.getPassengers(), FriendlyByteBuf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Object pivotTeleport(Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(Pivot pivot, BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + if (force) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } else if (bone.isTransformDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, flag ? 0 : 1), force); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), force); + bone.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 22, EntityDataSerializers.INT, color), force); + bone.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, val), force); + bone.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 12, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> EntityUtils.writeData(buf, 14, EntityDataSerializers.QUATERNION, quaternionf), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), force); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), force); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), force); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + return new ClientboundSetEntityDataPacket(buf); + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/SubHitboxParser.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..3b41b70 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/behavior/SubHitboxParser.java @@ -0,0 +1,163 @@ +package com.ticxo.modelengine.v1_20_R2.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer.SubHitbox; +import com.ticxo.modelengine.v1_20_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, subHitboxx) -> { + buf.writeVarInt(subHitboxx.getPivotId()); + buf.writeVarInt(subHitboxx.getHitboxId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection subHitboxes = renderer.getRendered().values(); + buf.writeVarInt(subHitboxes.size() * 2); + subHitboxes.forEach(subHitbox -> { + buf.writeVarInt(subHitbox.getPivotId()); + buf.writeVarInt(subHitbox.getHitboxId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitbox renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private Object pivotMove(SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitbox renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getHitboxId()); + return new ClientboundSetPassengersPacket(buf); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getHitboxId()); + renderer.getWidth().ifDirty(width -> EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, width), spawn); + renderer.getHeight().ifDirty(height -> EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, height), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/model/DisplayParser.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/model/DisplayParser.java new file mode 100644 index 0000000..ddb031d --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/model/DisplayParser.java @@ -0,0 +1,732 @@ +package com.ticxo.modelengine.v1_20_R2.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler.LODTracker; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.model.render.DisplayBone.BoneData; +import com.ticxo.modelengine.api.model.render.DisplayRenderer.Hitbox; +import com.ticxo.modelengine.api.model.render.DisplayRenderer.Pivot; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_20_R2.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static Constructor CUSTOM_PAYLOAD_CONSTRUCTOR; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size()); + destroy.forEach(buf::writeVarInt); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitboxDestroy.size()); + hitboxDestroy.forEach(buf::writeVarInt); + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)u -> this.displayData(u, null, boneData, false, transformOnly)); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(FriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CONSTRUCTOR == null) { + CUSTOM_PAYLOAD_CONSTRUCTOR = ClientboundCustomPayloadPacket.class.getDeclaredConstructor(FriendlyByteBuf.class); + CUSTOM_PAYLOAD_CONSTRUCTOR.setAccessible(true); + } + + return (Packet)CUSTOM_PAYLOAD_CONSTRUCTOR.newInstance(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData(BulkEntityDataEncoder encoder, UUID uuid, @Nullable LODTracker tracker, BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(Pivot pivot) { + return pivot.isOverridden() ? null : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Pivot pivot) { + if (pivot.isOverridden()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundSetPassengersPacket pivotMount(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + buf.writeVarInt(pivot.getPassengers().size()); + pivot.getPassengers().forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Object pivotTeleport(Pivot pivot) { + return !pivot.getPosition().isDirty() ? null : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + + private ClientboundAddEntityPacket displaySpawn(Pivot pivot, BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, @Nullable LODTracker tracker, BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + if (!force && update != 0) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + EntityUtils.writeData(buf, 22, EntityDataSerializers.INT, color); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, val); + } + }, force); + bone.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 12, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + EntityUtils.writeData(buf, 14, EntityDataSerializers.QUATERNION, quaternionf); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()); + } + }, force); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), force); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), force); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), force); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetEntityDataPacket displayVisibleData(BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))); + bone.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 22, EntityDataSerializers.INT, color)); + bone.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, val)); + bone.getBillboard().ifDirty(billboard -> EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundAddEntityPacket hitboxSpawn(Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getHitboxId()); + hitbox.getWidth().ifDirty(val -> EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, val), spawn); + hitbox.getHeight().ifDirty(val -> EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, val), spawn); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getShadowId()); + hitbox.getShadowRadius().ifDirty(val -> EntityUtils.writeData(buf, 18, EntityDataSerializers.FLOAT, val), spawn); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getPivotId()); + buf.writeVarInt(passengers.size()); + passengers.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + } +} diff --git a/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/vfx/VFXDisplayParser.java b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..e6c7844 --- /dev/null +++ b/nms/v1_20_R2/src/main/java/com/ticxo/modelengine/v1_20_R2/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,138 @@ +package com.ticxo.modelengine.v1_20_R2.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer.VFXModel; +import com.ticxo.modelengine.v1_20_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R2.network.utils.Packets; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_20_R2.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(2); + buf.writeVarInt(vfx.getPivotId()); + buf.writeVarInt(vfx.getModelId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXModel vfx) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getModelId()); + if (spawn) { + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, 1); + EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, 4096.0F); + EntityUtils.writeData(buf, 24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal()); + } else if (vfx.isModelDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + vfx.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), spawn); + vfx.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 12, EntityDataSerializers.VECTOR3, vector3f), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf), spawn); + vfx.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), spawn); + vfx.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, val), spawn); + buf.writeByte(255); + vfx.clearModelDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object teleport(VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXModel vfx) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(vfx.getModelId()); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSFields.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSFields.java new file mode 100644 index 0000000..8877314 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSFields.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_20_R3; + +import com.ticxo.modelengine.api.utils.ReflectionUtils.ReflectionEnum; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionEnum { + ENTITY_dimensions(Entity.class, "bh", "dimensions"), + ENTITY_eyeHeight(Entity.class, "bi", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "bZ", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "bj", "jumping"), + MOB_lookControl(Mob.class, "bK", "lookControl"), + MOB_moveControl(Mob.class, "bL", "moveControl"), + MOB_navigation(Mob.class, "bN", "navigation"), + MOB_goalSelector(Mob.class, "bO", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "bU", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "E", "clientIsFloating"), + SERVER_COMMON_PACKET_LISTENER_IMPL_connection(ServerCommonPacketListenerImpl.class, "c", "connection"), + MOVE_CONTROL_operation(MoveControl.class, "k", "operation"), + TRACKED_ENTITY_serverEntity(TrackedEntity.class, "b", "serverEntity"), + TRACKED_ENTITY_range(TrackedEntity.class, "d", "range"), + LEVEL_threadSafeRandom(Level.class, "f", "threadSafeRandom"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "a", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "a", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(Class target, String obfuscated, String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSHandler_v1_20_R3.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSHandler_v1_20_R3.java new file mode 100644 index 0000000..b71fe0b --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSHandler_v1_20_R3.java @@ -0,0 +1,190 @@ +package com.ticxo.modelengine.v1_20_R3; + +import com.mojang.math.MatrixUtil; +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.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.ui.AnvilHandler; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_20_R3.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_20_R3.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_20_R3.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_20_R3.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_20_R3.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_20_R3.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_20_R3.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_20_R3.parser.vfx.VFXDisplayParser; +import com.ticxo.modelengine.v1_20_R3.ui.AnvilHandlerImpl; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.entity.Entity; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_20_R3 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final AnvilHandler anvilHandler = new AnvilHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + FriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, new ClientboundSetPassengersPacket(byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(mountId); + buf.writeVarInt(passengerIds.size()); + passengerIds.forEach(buf::writeVarInt); + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(buf); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public AnvilHandler getAnvilHandler() { + return this.anvilHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSMethods.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSMethods.java new file mode 100644 index 0000000..feabd3e --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/NMSMethods.java @@ -0,0 +1,48 @@ +package com.ticxo.modelengine.v1_20_R3; + +import com.ticxo.modelengine.api.utils.ReflectionUtils.MethodEnum; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "d", "getInstrument", ItemStack.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityHandlerImpl.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..c9a3040 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityHandlerImpl.java @@ -0,0 +1,714 @@ +package com.ticxo.modelengine.v1_20_R3.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.nms.entity.EntityHandler.BoxRelToCam; +import com.ticxo.modelengine.api.nms.entity.EntityHandler.InteractionResult; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_20_R3.NMSFields; +import com.ticxo.modelengine.v1_20_R3.NMSMethods; +import com.ticxo.modelengine.v1_20_R3.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_20_R3.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_20_R3.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_20_R3.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_20_R3.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_20_R3.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_20_R3.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_20_R3.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_20_R3.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_20_R3.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.minecraft.core.Holder; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.UseAnim; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.v1_20_R3.CraftWorld; +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftItemStack; +import org.bukkit.craftbukkit.v1_20_R3.util.CraftLocation; +import org.bukkit.craftbukkit.v1_20_R3.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions((float)hitbox.getMaxWidth(), (float)hitbox.getHeight(), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + EntityUtils.nms(entity).setMaxUpStep((float)height); + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityType.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y + nmsEntity.getMyRidingOffset(this.dummyArmorStand); + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(entity.getEntityId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, data); + buf.writeByte(255); + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket(buf); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + if (oldNav instanceof WallClimberNavigation wallClimberNavigation) { + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + } else if (oldNav instanceof GroundPathNavigation groundPathNavigation) { + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + } else if (oldNav instanceof FlyingPathNavigation flyingPathNavigation) { + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + } else if (oldNav instanceof WaterBoundPathNavigation) { + newNav = new WaterBoundNavigationWrapper(mob); + } else { + if (!(oldNav instanceof AmphibiousPathNavigation amphibiousPathNavigation)) { + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var10) { + var10.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + ServerLevel level = ((CraftWorld)location.getWorld()).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + return EntityUtils.nms(entity).hurt(damageSource, amount); + } else { + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + } + + @Override + public InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case SUCCESS -> InteractionResult.SUCCESS; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.CONSUME_PARTIAL; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + default -> throw new IncompatibleClassChangeError(); + }; + } else { + return InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + FriendlyByteBuf pivotDataBuf = NetworkUtils.createByteBuf(); + pivotDataBuf.writeVarInt(DynamicHitbox.getPivotId()); + EntityUtils.writeData(pivotDataBuf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(pivotDataBuf, 8, EntityDataSerializers.FLOAT, 0.0F); + pivotDataBuf.writeByte(255); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket(pivotDataBuf); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + FriendlyByteBuf hitboxDataBuf = NetworkUtils.createByteBuf(); + hitboxDataBuf.writeVarInt(DynamicHitbox.getHitboxId()); + EntityUtils.writeData(hitboxDataBuf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(hitboxDataBuf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(hitboxDataBuf, 16, EntityDataSerializers.INT, 2); + hitboxDataBuf.writeByte(255); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(hitboxDataBuf); + FriendlyByteBuf mountBuf = NetworkUtils.createByteBuf(); + mountBuf.writeVarInt(DynamicHitbox.getPivotId()); + mountBuf.writeVarInt(1); + mountBuf.writeVarInt(DynamicHitbox.getHitboxId()); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket(mountBuf); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0 + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != UseAnim.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(player.getEntityId()); + EntityUtils.writeData(buf, 8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3)); + buf.writeByte(255); + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket(buf); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call(instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = level.getChunkSource().chunkMap.entityMap; + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = lvl.getChunkSource().chunkMap.entityMap; + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3D(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + BoxRelToCam relX = BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + BoxRelToCam relY = BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + BoxRelToCam relZ = BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == BoxRelToCam.INSIDE && relY == BoxRelToCam.INSIDE && relZ == BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.REDSTONE, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityMetadataID.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityMetadataID.java new file mode 100644 index 0000000..922c2dc --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityMetadataID.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.v1_20_R3.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityUtils.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityUtils.java new file mode 100644 index 0000000..21e842e --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/EntityUtils.java @@ -0,0 +1,27 @@ +package com.ticxo.modelengine.v1_20_R3.entity; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.syncher.EntityDataSerializer; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftEntity; + +public class EntityUtils { + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } + + public static void writeData(FriendlyByteBuf byteBuf, int id, EntityDataSerializer serializer, T val) { + int serializedId = EntityDataSerializers.getSerializedId(serializer); + byteBuf.writeByte(id); + byteBuf.writeVarInt(serializedId); + serializer.write(byteBuf, val); + } + + public static void writeDataUnsafe(FriendlyByteBuf byteBuf, int id, EntityDataSerializer serializer, Object val) { + int serializedId = EntityDataSerializers.getSerializedId(serializer); + byteBuf.writeByte(id); + byteBuf.writeVarInt(serializedId); + serializer.write(byteBuf, val); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/OcclusionClipContext.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/OcclusionClipContext.java new file mode 100644 index 0000000..451e27a --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v1_20_R3.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape(world, pos) == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (tX > 1.0 && tY > 1.0 && tZ > 1.0) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/TrackedEntityImpl.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..0c95f4b --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/TrackedEntityImpl.java @@ -0,0 +1,286 @@ +package com.ticxo.modelengine.v1_20_R3.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R3.NMSFields; +import com.ticxo.modelengine.v1_20_R3.NMSMethods; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } + + @Override + public boolean isViewerSetUnchanged() { + if ((!this.mayHaveForced || this.forcedPairing.isEmpty() && this.forcedRemove.isEmpty()) && this.playerPredicate == DEFAULT_PREDICATE) { + if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } else { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/BodyRotationControlWrapper.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..86c1e3b --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_20_R3.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/LookControlWrapper.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..ec15327 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/LookControlWrapper.java @@ -0,0 +1,143 @@ +package com.ticxo.modelengine.v1_20_R3.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; +import org.spigotmc.ActivationRange; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/MoveControlWrapper.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..cfcc18b --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/controller/MoveControlWrapper.java @@ -0,0 +1,247 @@ +package com.ticxo.modelengine.v1_20_R3.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.mount.controller.MountController.MountInput; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R3.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.craftbukkit.v1_20_R3.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + controller.setInput(new MountInput()); + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/hitbox/HitboxEntityImpl.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..018c50d --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,294 @@ +package com.ticxo.modelengine.v1_20_R3.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_20_R3.NMSFields; +import com.ticxo.modelengine.v1_20_R3.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftEntity; +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.v1_20_R3.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public Iterable getArmorSlots() { + return this.armorItems; + } + + public ItemStack getItemBySlot(EquipmentSlot slot) { + return switch (slot.getType()) { + case HAND -> (ItemStack)this.handItems.get(slot.getIndex()); + case ARMOR -> (ItemStack)this.armorItems.get(slot.getIndex()); + default -> throw new IncompatibleClassChangeError(); + }; + } + + public void setItemSlot(EquipmentSlot slot, ItemStack stack) { + this.verifyEquippedItem(stack); + switch (slot.getType()) { + case HAND: + this.onEquipItem(slot, this.handItems.set(slot.getIndex(), stack), stack); + break; + case ARMOR: + this.onEquipItem(slot, this.armorItems.set(slot.getIndex(), stack), stack); + } + } + + public boolean isInvisible() { + return true; + } + + public void push(Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox() { + if (this.subHitbox == null) { + return super.makeBoundingBox(); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurt(DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurt(source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return this.bone.getActiveModel().getModeledEntity().getBase().hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, + entity, + new Vector(0, 0, 0), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + com.ticxo.modelengine.api.nms.entity.EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact( + this, + player.getBukkitEntity(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND + ); + + return switch (result) { + case SUCCESS, SUCCESS_NO_ITEM_USED -> InteractionResult.SUCCESS; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.CONSUME_PARTIAL; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }; + } + } + + public boolean shouldBeSaved() { + return false; + } + + public CraftEntity getBukkitEntity() { + CraftEntity bukkitEntity = this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + CraftEntity var5 = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(var5); + return var5; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/hitbox/OBB.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/hitbox/OBB.java new file mode 100644 index 0000000..218d746 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_20_R3.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..94d6efa --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_20_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..6fd4986 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/GroundNavigationWrapper.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..f154a79 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..ca30f0d --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..1c113b4 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_20_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/ModelEngineChannelHandler.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..a98c8ab --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/ModelEngineChannelHandler.java @@ -0,0 +1,439 @@ +package com.ticxo.modelengine.v1_20_R3.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.mount.controller.MountController.MountInput; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R3.NMSFields; +import com.ticxo.modelengine.v1_20_R3.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntListIterator; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + + for (Packet p : this.writeInterceptors.acceptPost(result)) { + list.add(p); + } + } + } + + if (!list.isEmpty()) { + Packet var13 = new ClientboundBundlePacket(list); + super.write(ctx, var13, promise); + } + } else { + Packet var14 = this.writeInterceptors.accept(packet); + if (var14 == null) { + return; + } + + Collection post = this.writeInterceptors.acceptPost(var14); + if (post.isEmpty()) { + super.write(ctx, var14, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var14); + + for (Packet p : post) { + list.add(p); + } + + Packet var15 = new ClientboundBundlePacket(list); + super.write(ctx, var15, promise); + } + } + } catch (Throwable var12) { + var12.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + ArrayList list = new ArrayList<>(); + model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT).ifPresent(behaviorRenderer -> { + if (behaviorRenderer instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + CollectionDataTracker ids = mount.getPassengers(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(mount.getMountId()); + buf.writeVarInt(ids.size()); + ids.forEach(buf::writeVarInt); + list.add(new ClientboundSetPassengersPacket(buf)); + } + } + }); + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int size = buf.readVarInt(); + HashSet set = new HashSet<>(size); + + for (int i = 0; i < size; i++) { + int id = buf.readVarInt(); + this.markViewersDirty(id); + if (ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE) { + set.add(id); + } + } + + if (set.size() == size) { + return packet; + } else { + buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(set.size()); + + for (int id : set) { + buf.writeVarInt(id); + } + + return new ClientboundRemoveEntitiesPacket(buf); + } + } + + private > Packet handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int id = buf.readVarInt(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private > Packet handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(packet.id()); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + buf.writeByte(255); + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int id = buf.readVarInt(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + if (!changed) { + return packet; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(packet.getVehicle()); + buf.writeVarInt(merged.size()); + IntListIterator var16 = merged.iterator(); + + while (var16.hasNext()) { + int idx = (Integer)var16.next(); + buf.writeVarInt(idx); + } + + return new ClientboundSetPassengersPacket(buf); + } + } + } + } + + private ServerboundInteractPacket handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readData(packet); + int entityId = buf.readVarInt(); + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, packet) : packet; + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountInput input = controller.getInput(); + if (input == null) { + controller.setInput(new MountInput(inputPacket.getXxa(), inputPacket.getZza(), inputPacket.isJumping(), inputPacket.isShiftKeyDown())); + } else { + input.setSide(inputPacket.getXxa()); + input.setFront(inputPacket.getZza()); + input.setJump(inputPacket.isJumping()); + input.setSneak(inputPacket.isShiftKeyDown()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + return packet; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/NetworkHandlerImpl.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..a8bb069 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/NetworkHandlerImpl.java @@ -0,0 +1,140 @@ +package com.ticxo.modelengine.v1_20_R3.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R3.NMSFields; +import com.ticxo.modelengine.v1_20_R3.network.utils.Bundler; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/patch/PatchedServerGamePacketListener.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..77c137a --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,408 @@ +package com.ticxo.modelengine.v1_20_R3.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent.Action; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R3.NMSMethods; +import java.util.Arrays; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.v1_20_R3.CraftServer; +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer; +import org.bukkit.craftbukkit.v1_20_R3.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().serverLevel()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.serverLevel(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + final ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + null + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT_ON, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + position + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.INTERACT_ON, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + position + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + Action.ATTACK, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, null); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, pos); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent( + craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND, null + ); + } + } + ); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= ServerGamePacketListenerImpl.MAX_INTERACTION_DISTANCE)) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelected().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + entity.getEntityData().resendPossiblyDesyncedEntity(player); + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem) { + entity.getEntityData().refresh(player); + if (entity instanceof Allay allay) { + connection.send( + new ClientboundSetEquipmentPacket( + entity.getId(), + Arrays.stream(net.minecraft.world.entity.EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.stripMeta(allay.getItemBySlot(slot), true))) + .collect(Collectors.toList()) + ) + ); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.serverLevel()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.serverLevel(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level().clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.isSameItemSameTags(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand, + movingobjectpositionblock.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, org.bukkit.event.block.Action.RIGHT_CLICK_AIR, itemstack, enumhand + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.resyncUsingItem(player); + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent( + CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacket packet, InteractionHand hand, @Nullable Vec3 vector + ) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.isAttack(), + hand == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND, + vector != null ? new Vector(vector.x, vector.y, vector.z) : null + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..85df442 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,63 @@ +package com.ticxo.modelengine.v1_20_R3.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper extends ServerboundInteractPacket { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, ServerboundInteractPacket original) { + super(NetworkUtils.readData(original)); + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + } + + public void write(FriendlyByteBuf var0) { + this.original.write(var0); + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/BulkEntityDataEncoder.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..f22b1d6 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_20_R3.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/Bundler.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/Bundler.java new file mode 100644 index 0000000..eea1b96 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_20_R3.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.get(this.bundles.size() - 1); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.get(this.bundles.size() - 1); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet p : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(p); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/NetworkUtils.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/NetworkUtils.java new file mode 100644 index 0000000..b4b48a1 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/NetworkUtils.java @@ -0,0 +1,271 @@ +package com.ticxo.modelengine.v1_20_R3.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler.LODTracker; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_20_R3.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.util.Collection; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static FriendlyByteBuf createByteBuf() { + return new FriendlyByteBuf(Unpooled.buffer()); + } + + public static FriendlyByteBuf createByteBuf(Consumer consumer) { + FriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static FriendlyByteBuf readData(Packet packet) { + FriendlyByteBuf buf = createByteBuf(); + packet.write(buf); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + FriendlyByteBuf buf = createByteBuf(); + buf.writeVarInt(id); + buf.writeDouble(pos.x); + buf.writeDouble(pos.y - 0.375); + buf.writeDouble(pos.z); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + ClientboundTeleportEntityPacket tpHigher = new ClientboundTeleportEntityPacket(buf); + buf = createByteBuf(); + buf.writeVarInt(id); + buf.writeDouble(pos.x); + buf.writeDouble(pos.y - 0.5); + buf.writeDouble(pos.z); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + ClientboundTeleportEntityPacket tpLower = new ClientboundTeleportEntityPacket(buf); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Packets.PacketSupplier lodWrapper(ModeledEntity modeledEntity, BiFunction> packetFunction) { + return uuid -> { + LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/PacketInterceptor.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..14a86e8 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/PacketInterceptor.java @@ -0,0 +1,83 @@ +package com.ticxo.modelengine.v1_20_R3.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor { + private final Map, PacketInterceptor.Modifier> registry = Maps.newConcurrentMap(); + private final Map, PacketInterceptor.Listener> postRegistry = Maps.newConcurrentMap(); + + public PacketInterceptor register(Class clazz, Function function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public PacketInterceptor registerPost(Class clazz, Function> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor.Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor.Listener listener = this.postRegistry.get(original.getClass()); + return (Collection)(listener != null ? listener.listen(original) : List.of()); + } + } + + static class Listener { + private final Class clazz; + private final Function> function; + + public Collection listen(Packet original) { + try { + Collection collection = this.function.apply(this.clazz.cast(original)); + return (Collection)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(Class clazz, Function> function) { + this.clazz = clazz; + this.function = function; + } + } + + static class Modifier { + private final Class clazz; + private final Function function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(Class clazz, Function function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/Packets.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/Packets.java new file mode 100644 index 0000000..195c4f6 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_20_R3.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/HeldItemParser.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..a95a736 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/HeldItemParser.java @@ -0,0 +1,198 @@ +package com.ticxo.modelengine.v1_20_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer.Item; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.v1_20_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.Packets; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftItemStack; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size()); + destroy.forEach((s, item) -> buf.writeVarInt(item.getId())); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Map items = renderer.getRendered(); + buf.writeVarInt(1 + items.size()); + buf.writeVarInt(renderer.getId()); + items.forEach((s, item) -> buf.writeVarInt(item.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)16); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + if (spawn) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, 1); + EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, this.viewRange); + } else if (renderer.isTransformDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + renderer.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), spawn); + renderer.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 22, EntityDataSerializers.INT, color), spawn); + renderer.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 12, EntityDataSerializers.VECTOR3, vector3f), spawn); + renderer.getRotation().ifDirty(quaternionf -> EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf), spawn); + renderer.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), spawn); + renderer.getDisplay() + .ifDirty(display -> EntityUtils.writeData(buf, 24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(location.getX(), location.getY(), location.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + buf.writeDouble(location.getX()); + buf.writeDouble(location.getY()); + buf.writeDouble(location.getZ()); + buf.writeByte(0); + buf.writeByte(0); + buf.writeBoolean(false); + return new ClientboundTeleportEntityPacket(buf); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getId()); + CollectionDataTracker set = renderer.getPassengers(); + buf.writeVarInt(set.size()); + set.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/LeashParser.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/LeashParser.java new file mode 100644 index 0000000..80cd2f6 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/LeashParser.java @@ -0,0 +1,176 @@ +package com.ticxo.modelengine.v1_20_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer.Leash; +import com.ticxo.modelengine.v1_20_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Map leashes = renderer.getRendered(); + buf.writeVarInt(leashes.size()); + leashes.forEach((s, leash) -> buf.writeVarInt(leash.getLeashId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos); + } + + private ClientboundAddEntityPacket leashSpawn(Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.SLIME, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getLeashId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetEntityDataPacket leashData(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getLeashId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, 0); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket mount(Leash renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(buf); + } + + private Object move(Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos); + } + } + + private ClientboundSetEntityLinkPacket link(Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeInt(renderer.getLeashId()); + buf.writeInt(renderer.getConnected().get()); + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(buf); + } + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/MountParser.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/MountParser.java new file mode 100644 index 0000000..d033432 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/MountParser.java @@ -0,0 +1,244 @@ +package com.ticxo.modelengine.v1_20_R3.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer.Mount; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket.AttributeSnapshot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, mount) -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getMountId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection mounts = renderer.getRendered().values(); + buf.writeVarInt(mounts.size() * 2); + mounts.forEach(mount -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getMountId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(Mount renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket mountSpawn(Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)16); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket pivotMount(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getMountId()); + return new ClientboundSetPassengersPacket(buf); + } + + private ClientboundSetPassengersPacket mount(Mount renderer) { + CollectionDataTracker ids = renderer.getPassengers(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + buf.writeVarInt(ids.size()); + ids.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Packets.PacketSupplier pivotMove(Mount renderer) { + return NetworkUtils.createPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(Mount renderer) { + FriendlyByteBuf rot = NetworkUtils.createByteBuf(); + rot.writeVarInt(renderer.getMountId()); + rot.writeByte(renderer.getYaw().get()); + rot.writeByte(0); + rot.writeBoolean(false); + return Rot.read(rot); + } + + private ClientboundSetEntityDataPacket mountHealth(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getMountId()); + EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, renderer.getHealth().get()); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(Mount renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection attributes = Lists.newArrayList(); + attributes.add(new AttributeSnapshot(Attributes.MAX_HEALTH, renderer.getMaxHealth().get().floatValue(), Lists.newArrayList())); + buf.writeVarInt(renderer.getMountId()); + buf.writeCollection(attributes, (buf2, attribute) -> { + buf2.writeResourceLocation(BuiltInRegistries.ATTRIBUTE.getKey(attribute.getAttribute())); + buf2.writeDouble(attribute.getBase()); + buf2.writeCollection(attribute.getModifiers(), (buf3, modifier) -> { + buf3.writeUUID(modifier.getId()); + buf3.writeDouble(modifier.getAmount()); + buf3.writeByte(modifier.getOperation().toValue()); + }); + }); + return new ClientboundUpdateAttributesPacket(buf); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/NameTagParser.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..ebe0572 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/NameTagParser.java @@ -0,0 +1,195 @@ +package com.ticxo.modelengine.v1_20_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer.NameTag; +import com.ticxo.modelengine.v1_20_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Component.Serializer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, mount) -> { + buf.writeVarInt(mount.getPivotId()); + buf.writeVarInt(mount.getTagId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection nameTags = renderer.getRendered().values(); + buf.writeVarInt(nameTags.size() * 2); + nameTags.forEach(nameTag -> { + buf.writeVarInt(nameTag.getPivotId()); + buf.writeVarInt(nameTag.getTagId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + if (spawn) { + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 1, EntityDataSerializers.INT, Integer.MAX_VALUE); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + } + + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getTagId()); + renderer.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), spawn); + renderer.getTextOpacity().ifDirty(flag -> EntityUtils.writeData(buf, 26, EntityDataSerializers.BYTE, flag), spawn); + renderer.getBackgroundColor().ifDirty(flag -> EntityUtils.writeData(buf, 25, EntityDataSerializers.INT, flag), spawn); + renderer.getLineWidth().ifDirty(flag -> EntityUtils.writeData(buf, 24, EntityDataSerializers.INT, flag), spawn); + renderer.getStyle().ifDirty(flags -> EntityUtils.writeData(buf, 27, EntityDataSerializers.BYTE, flags), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new IncompatibleClassChangeError(); + }; + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, value); + }, spawn); + renderer.getJsonString().ifDirty(jsonString -> { + if (jsonString == null) { + EntityUtils.writeData(buf, 23, EntityDataSerializers.COMPONENT, Component.empty()); + } else { + EntityUtils.writeData(buf, 23, EntityDataSerializers.COMPONENT, Serializer.fromJson(jsonString)); + } + }, spawn); + renderer.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, val), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object pivotMove(NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTag renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getTagId()); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/SegmentParser.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..3c10c12 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/SegmentParser.java @@ -0,0 +1,220 @@ +package com.ticxo.modelengine.v1_20_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer.Pivot; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer.SegmentDisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayBone.BoneData; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentDisplayBone bone : pivot.getRendered().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + HashSet destroy = new HashSet<>(); + + for (Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeCollection(destroy, FriendlyByteBuf::writeVarInt); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetPassengersPacket pivotMount(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + buf.writeCollection(pivot.getPassengers(), FriendlyByteBuf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Object pivotTeleport(Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(Pivot pivot, BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + if (force) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } else if (bone.isTransformDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, flag ? 0 : 1), force); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), force); + bone.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 22, EntityDataSerializers.INT, color), force); + bone.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, val), force); + bone.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 12, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> EntityUtils.writeData(buf, 14, EntityDataSerializers.QUATERNION, quaternionf), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), force); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), force); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), force); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + return new ClientboundSetEntityDataPacket(buf); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/SubHitboxParser.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..b9ed63c --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/behavior/SubHitboxParser.java @@ -0,0 +1,163 @@ +package com.ticxo.modelengine.v1_20_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer.SubHitbox; +import com.ticxo.modelengine.v1_20_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.Packets; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size() * 2); + destroy.forEach((s, subHitboxx) -> { + buf.writeVarInt(subHitboxx.getPivotId()); + buf.writeVarInt(subHitboxx.getHitboxId()); + }); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + Collection subHitboxes = renderer.getRendered().values(); + buf.writeVarInt(subHitboxes.size() * 2); + subHitboxes.forEach(subHitbox -> { + buf.writeVarInt(subHitbox.getPivotId()); + buf.writeVarInt(subHitbox.getHitboxId()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitbox renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private Object pivotMove(SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitbox renderer) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(renderer.getHitboxId()); + return new ClientboundSetPassengersPacket(buf); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(renderer.getHitboxId()); + renderer.getWidth().ifDirty(width -> EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, width), spawn); + renderer.getHeight().ifDirty(height -> EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, height), spawn); + buf.writeByte(255); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/model/DisplayParser.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/model/DisplayParser.java new file mode 100644 index 0000000..c2dcdac --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/model/DisplayParser.java @@ -0,0 +1,732 @@ +package com.ticxo.modelengine.v1_20_R3.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler.LODTracker; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.model.render.DisplayBone.BoneData; +import com.ticxo.modelengine.api.model.render.DisplayRenderer.Hitbox; +import com.ticxo.modelengine.api.model.render.DisplayRenderer.Pivot; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static Constructor CUSTOM_PAYLOAD_CONSTRUCTOR; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(destroy.size()); + destroy.forEach(buf::writeVarInt); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitboxDestroy.size()); + hitboxDestroy.forEach(buf::writeVarInt); + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(buf))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)u -> this.displayData(u, null, boneData, false, transformOnly)); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(FriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CONSTRUCTOR == null) { + CUSTOM_PAYLOAD_CONSTRUCTOR = ClientboundCustomPayloadPacket.class.getDeclaredConstructor(FriendlyByteBuf.class); + CUSTOM_PAYLOAD_CONSTRUCTOR.setAccessible(true); + } + + return (Packet)CUSTOM_PAYLOAD_CONSTRUCTOR.newInstance(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData(BulkEntityDataEncoder encoder, UUID uuid, @Nullable LODTracker tracker, BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(Pivot pivot) { + return pivot.isOverridden() ? null : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(Pivot pivot) { + if (pivot.isOverridden()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundSetPassengersPacket pivotMount(Pivot pivot) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(pivot.getId()); + buf.writeVarInt(pivot.getPassengers().size()); + pivot.getPassengers().forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + + private Object pivotTeleport(Pivot pivot) { + return !pivot.getPosition().isDirty() ? null : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + + private ClientboundAddEntityPacket displaySpawn(Pivot pivot, BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, @Nullable LODTracker tracker, BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + if (!force && update != 0) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + EntityUtils.writeData(buf, 22, EntityDataSerializers.INT, color); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, val); + } + }, force); + bone.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 12, EntityDataSerializers.VECTOR3, vector3f), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + EntityUtils.writeData(buf, 14, EntityDataSerializers.QUATERNION, quaternionf); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()); + } + }, force); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F), force); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), force); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()), force); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundSetEntityDataPacket displayVisibleData(BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(boneData.getId()); + bone.getGlowing().ifDirty(flag -> EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))); + bone.getGlowColor().ifDirty(color -> EntityUtils.writeData(buf, 22, EntityDataSerializers.INT, color)); + bone.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, val)); + bone.getBillboard().ifDirty(billboard -> EntityUtils.writeData(buf, 15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + bone.getVisibility().ifDirty(flag -> EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)); + boneData.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))); + bone.getDisplay().ifDirty(display -> EntityUtils.writeData(buf, 24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())); + buf.writeByte(255); + this.cleanupQueue.add(bone::clearDirty); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private ClientboundAddEntityPacket hitboxSpawn(Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getHitboxId()); + hitbox.getWidth().ifDirty(val -> EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, val), spawn); + hitbox.getHeight().ifDirty(val -> EntityUtils.writeData(buf, 9, EntityDataSerializers.FLOAT, val), spawn); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getShadowId()); + hitbox.getShadowRadius().ifDirty(val -> EntityUtils.writeData(buf, 18, EntityDataSerializers.FLOAT, val), spawn); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(hitbox.getPivotId()); + buf.writeVarInt(passengers.size()); + passengers.forEach(buf::writeVarInt); + return new ClientboundSetPassengersPacket(buf); + } + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/vfx/VFXDisplayParser.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..13f4296 --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,138 @@ +package com.ticxo.modelengine.v1_20_R3.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer.VFXModel; +import com.ticxo.modelengine.v1_20_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.Packets; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXModel vfx) { + if (!targets.isEmpty()) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(2); + buf.writeVarInt(vfx.getPivotId()); + buf.writeVarInt(vfx.getModelId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(buf)); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXModel vfx) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getPivotId()); + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.FLOAT, 0.0F); + buf.writeByte(255); + return new ClientboundSetEntityDataPacket(buf); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getModelId()); + if (spawn) { + EntityUtils.writeData(buf, 0, EntityDataSerializers.BYTE, (byte)32); + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + EntityUtils.writeData(buf, 9, EntityDataSerializers.INT, 1); + EntityUtils.writeData(buf, 17, EntityDataSerializers.FLOAT, 4096.0F); + EntityUtils.writeData(buf, 24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal()); + } else if (vfx.isModelDirty()) { + EntityUtils.writeData(buf, 8, EntityDataSerializers.INT, 0); + } + + vfx.getPosition().ifDirty(vector3f -> EntityUtils.writeData(buf, 11, EntityDataSerializers.VECTOR3, vector3f), spawn); + vfx.getScale().ifDirty(vector3f -> EntityUtils.writeData(buf, 12, EntityDataSerializers.VECTOR3, vector3f), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> EntityUtils.writeData(buf, 13, EntityDataSerializers.QUATERNION, quaternionf), spawn); + vfx.getModel().ifDirty(itemStack -> EntityUtils.writeData(buf, 23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)), spawn); + vfx.getBrightness().ifDirty(val -> EntityUtils.writeData(buf, 16, EntityDataSerializers.INT, val), spawn); + buf.writeByte(255); + vfx.clearModelDirty(); + return new ClientboundSetEntityDataPacket(buf); + } + } + + private Object teleport(VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXModel vfx) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(vfx.getModelId()); + return new ClientboundSetPassengersPacket(buf); + } +} diff --git a/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/ui/AnvilHandlerImpl.java b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/ui/AnvilHandlerImpl.java new file mode 100644 index 0000000..679b90e --- /dev/null +++ b/nms/v1_20_R3/src/main/java/com/ticxo/modelengine/v1_20_R3/ui/AnvilHandlerImpl.java @@ -0,0 +1,111 @@ +package com.ticxo.modelengine.v1_20_R3.ui; + +import com.ticxo.modelengine.api.nms.ui.AnvilHandler; +import com.ticxo.modelengine.api.nms.ui.AnvilHandler.Menu; +import com.ticxo.modelengine.v1_20_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R3.network.utils.Packets; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; +import java.util.function.Supplier; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ClientboundContainerClosePacket; +import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; +import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket; +import net.minecraft.network.protocol.game.ClientboundSetTimePacket; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import org.bukkit.entity.Player; + +public class AnvilHandlerImpl implements AnvilHandler { + private final Map anvilId = new HashMap<>(); + + @Override + public void openAnvil(Player player, Function onInput, Supplier onClose) { + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + int id = nmsPlayer.nextContainerCounter(); + this.anvilId.put(player.getUniqueId(), new Menu(id, onInput, onClose)); + this.reopenAnvil(player); + } + + @Override + public void reopenAnvil(Player player) { + Menu menu = this.getAnvilMenu(player); + if (menu != null) { + ItemStack item = new ItemStack(Blocks.STONE).setHoverName(Component.empty()); + final ClientboundOpenScreenPacket anvilScreen = new ClientboundOpenScreenPacket(menu.getId(), MenuType.ANVIL, Component.empty()); + final ClientboundContainerSetSlotPacket setItem = new ClientboundContainerSetSlotPacket(menu.getId(), 0, 0, item); + NetworkUtils.sendBundled(player.getUniqueId(), new Packets() { + { + this.add(anvilScreen); + this.add(setItem); + } + }); + } + } + + @Override + public void consumeConfirm(Player player) { + Menu callback = this.anvilId.get(player.getUniqueId()); + if (callback != null && callback.confirm()) { + this.reopenAnvil(player); + } else { + this.closeAnvil(player); + } + } + + @Override + public void consumeClose(Player player) { + Menu callback = this.anvilId.get(player.getUniqueId()); + if (callback != null && callback.close()) { + this.reopenAnvil(player); + } else { + this.removeAnvil(player); + } + } + + @Override + public void removeAnvil(Player player) { + Menu callback = this.anvilId.remove(player.getUniqueId()); + if (callback != null) { + callback.close(); + } + + Level world = EntityUtils.nms(player).level(); + ClientboundSetTimePacket packet = new ClientboundSetTimePacket( + world.getGameTime(), world.getDayTime(), world.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT) + ); + NetworkUtils.send(player.getUniqueId(), packet); + } + + @Override + public void closeAnvil(Player player) { + final Menu callback = this.anvilId.remove(player.getUniqueId()); + if (callback != null) { + callback.close(); + final Level world = EntityUtils.nms(player).level(); + NetworkUtils.sendBundled(player.getUniqueId(), new Packets() { + { + this.add(new ClientboundContainerClosePacket(callback.getId())); + this.add(new ClientboundSetTimePacket(world.getGameTime(), world.getDayTime(), world.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT))); + } + }); + } + } + + @Override + public boolean isListening(Player player) { + return this.anvilId.containsKey(player.getUniqueId()); + } + + @Override + public Menu getAnvilMenu(Player player) { + return this.anvilId.get(player.getUniqueId()); + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSFields.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSFields.java new file mode 100644 index 0000000..8011da8 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSFields.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_20_R4; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionUtils.ReflectionEnum { + ENTITY_dimensions(Entity.class, "bf", "dimensions"), + ENTITY_eyeHeight(Entity.class, "bg", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "cf", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "bn", "jumping"), + MOB_lookControl(Mob.class, "bO", "lookControl"), + MOB_moveControl(Mob.class, "bP", "moveControl"), + MOB_navigation(Mob.class, "bR", "navigation"), + MOB_goalSelector(Mob.class, "bS", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "bZ", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "I", "clientIsFloating"), + SERVER_COMMON_PACKET_LISTENER_IMPL_connection(ServerCommonPacketListenerImpl.class, "e", "connection"), + MOVE_CONTROL_operation(MoveControl.class, "k", "operation"), + TRACKED_ENTITY_serverEntity(TrackedEntity.class, "b", "serverEntity"), + TRACKED_ENTITY_range(TrackedEntity.class, "d", "range"), + LEVEL_threadSafeRandom(Level.class, "f", "threadSafeRandom"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "a", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "b", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(final Class target, final String obfuscated, final String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSHandler_v1_20_R4.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSHandler_v1_20_R4.java new file mode 100644 index 0000000..c641030 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSHandler_v1_20_R4.java @@ -0,0 +1,179 @@ +package com.ticxo.modelengine.v1_20_R4; + +import com.mojang.math.MatrixUtil; +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.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_20_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_20_R4.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R4.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_20_R4.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_20_R4.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_20_R4.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_20_R4.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_20_R4.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_20_R4.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.entity.Entity; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_20_R4 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + FriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, NetworkUtils.create(ClientboundSetPassengersPacket.class, byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(EntityContainer.of(mountId, passengerIds)); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSMethods.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSMethods.java new file mode 100644 index 0000000..c7f0d20 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/NMSMethods.java @@ -0,0 +1,48 @@ +package com.ticxo.modelengine.v1_20_R4; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements ReflectionUtils.MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "d", "getInstrument", ItemStack.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityContainer.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityContainer.java new file mode 100644 index 0000000..ebc7fe0 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityContainer.java @@ -0,0 +1,52 @@ +package com.ticxo.modelengine.v1_20_R4.entity; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.syncher.SynchedEntityData.Builder; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.ApiStatus.Internal; + +@Internal +public class EntityContainer extends Entity { + public static EntityContainer of(int id) { + return new EntityContainer(id); + } + + public static Entity of(int id, int... passengerIds) { + EntityContainer container = of(id); + container.setPassengers(Arrays.stream(passengerIds).mapToObj(EntityContainer::new).toList()); + return container; + } + + public static Entity of(int id, Collection passengerIds) { + EntityContainer container = of(id); + container.setPassengers(passengerIds.stream().map(EntityContainer::new).toList()); + return container; + } + + private EntityContainer(int id) { + super(EntityType.INTERACTION, null); + this.setId(id); + this.setPosRaw(0.0, 0.0, 0.0); + this.setRot(0.0F, 0.0F); + this.setOnGround(false); + } + + protected void setPassengers(List passengers) { + this.passengers = ImmutableList.copyOf(passengers); + } + + protected void defineSynchedData(@NotNull Builder builder) { + } + + protected void readAdditionalSaveData(@NotNull CompoundTag nbt) { + } + + protected void addAdditionalSaveData(@NotNull CompoundTag nbt) { + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityHandlerImpl.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..4252d94 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityHandlerImpl.java @@ -0,0 +1,731 @@ +package com.ticxo.modelengine.v1_20_R4.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_20_R4.NMSFields; +import com.ticxo.modelengine.v1_20_R4.NMSMethods; +import com.ticxo.modelengine.v1_20_R4.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_20_R4.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_20_R4.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_20_R4.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_20_R4.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_20_R4.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_20_R4.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_20_R4.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_20_R4.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_20_R4.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.minecraft.core.Holder; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityAttachments; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.UseAnim; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + float width = (float)hitbox.getMaxWidth(); + float height = (float)hitbox.getHeight(); + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions(width, height, (float)hitbox.getEyeHeight(), EntityAttachments.createDefault(width, height), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + if (EntityUtils.nms(entity) instanceof LivingEntity living) { + living.getAttributes().registerAttribute(Attributes.STEP_HEIGHT); + Objects.requireNonNull(living.getAttribute(Attributes.STEP_HEIGHT)).setBaseValue(height); + } + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityType.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y - nmsEntity.getVehicleAttachmentPoint(this.dummyArmorStand).y; + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + entity.getEntityId(), List.of(new DataValue(0, EntityDataSerializers.BYTE, data)) + ); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + switch (oldNav) { + case WallClimberNavigation wallClimberNavigation: + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + break; + case GroundPathNavigation groundPathNavigation: + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + break; + case FlyingPathNavigation flyingPathNavigation: + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + break; + case WaterBoundPathNavigation waterBoundPathNavigation: + newNav = new WaterBoundNavigationWrapper(mob); + break; + case AmphibiousPathNavigation amphibiousPathNavigation: + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + break; + default: + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var13) { + var13.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + ServerLevel level = ((CraftWorld)location.getWorld()).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + return EntityUtils.nms(entity).hurt(damageSource, amount); + } else { + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + } + + @Override + public EntityHandler.InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case SUCCESS -> EntityHandler.InteractionResult.SUCCESS; + case SUCCESS_NO_ITEM_USED -> EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED; + case CONSUME -> EntityHandler.InteractionResult.CONSUME; + case CONSUME_PARTIAL -> EntityHandler.InteractionResult.CONSUME_PARTIAL; + case PASS -> EntityHandler.InteractionResult.PASS; + case FAIL -> EntityHandler.InteractionResult.FAIL; + default -> throw new MatchException(null, null); + }; + } else { + return EntityHandler.InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket( + DynamicHitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA + ); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(DynamicHitbox.getHitboxId(), EntityUtils.DEFAULT_SLIME_DATA); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket( + EntityContainer.of(DynamicHitbox.getPivotId(), DynamicHitbox.getHitboxId()) + ); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0 + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != UseAnim.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + player.getEntityId(), List.of(new DataValue(8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3))) + ); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call( + instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack, nmsPlayer.registryAccess() + ); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public Float getCameraEyeHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return nmsEntity.getDimensions(Pose.STANDING).eyeHeight(); + } + + @Override + public Float getCameraPivotHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + EntityDimensions dimensions = nmsEntity.getDimensions(nmsEntity.getPose()); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 attachment = ReflectionUtils.call(nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, dimensions, 1.0F); + return attachment == null ? null : (float)(dimensions.eyeHeight() - attachment.y); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = level.getChunkSource().chunkMap.entityMap; + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = lvl.getChunkSource().chunkMap.entityMap; + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3D(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + EntityHandler.BoxRelToCam relX = EntityHandler.BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + EntityHandler.BoxRelToCam relY = EntityHandler.BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + EntityHandler.BoxRelToCam relZ = EntityHandler.BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == EntityHandler.BoxRelToCam.INSIDE && relY == EntityHandler.BoxRelToCam.INSIDE && relZ == EntityHandler.BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.DUST, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityMetadataID.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityMetadataID.java new file mode 100644 index 0000000..f41fe7c --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityMetadataID.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.v1_20_R4.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityUtils.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityUtils.java new file mode 100644 index 0000000..8dcb2a3 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/EntityUtils.java @@ -0,0 +1,32 @@ +package com.ticxo.modelengine.v1_20_R4.entity; + +import java.util.List; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.entity.CraftEntity; + +public class EntityUtils { + public static final List> DEFAULT_AREA_EFFECT_CLOUD_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(8, EntityDataSerializers.FLOAT, 0.0F) + ); + public static final List> DEFAULT_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(16, EntityDataSerializers.INT, 2) + ); + public static final List> LEASH_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(16, EntityDataSerializers.INT, 0) + ); + public static final List> DEFAULT_ARMOR_STAND_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(15, EntityDataSerializers.BYTE, (byte)16) + ); + + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/OcclusionClipContext.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/OcclusionClipContext.java new file mode 100644 index 0000000..4ca932b --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v1_20_R4.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape(world, pos) == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (tX > 1.0 && tY > 1.0 && tZ > 1.0) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/TrackedEntityImpl.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..690a6c8 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/TrackedEntityImpl.java @@ -0,0 +1,286 @@ +package com.ticxo.modelengine.v1_20_R4.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R4.NMSFields; +import com.ticxo.modelengine.v1_20_R4.NMSMethods; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } + + @Override + public boolean isViewerSetUnchanged() { + if ((!this.mayHaveForced || this.forcedPairing.isEmpty() && this.forcedRemove.isEmpty()) && this.playerPredicate == DEFAULT_PREDICATE) { + if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } else { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/BodyRotationControlWrapper.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..ed16f51 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_20_R4.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/LookControlWrapper.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..f0b0440 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/LookControlWrapper.java @@ -0,0 +1,143 @@ +package com.ticxo.modelengine.v1_20_R4.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; +import org.spigotmc.ActivationRange; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/MoveControlWrapper.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..bc5240d --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/controller/MoveControlWrapper.java @@ -0,0 +1,246 @@ +package com.ticxo.modelengine.v1_20_R4.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R4.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + controller.setInput(new MountController.MountInput()); + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/hitbox/HitboxEntityImpl.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..9fe0f22 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,297 @@ +package com.ticxo.modelengine.v1_20_R4.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_20_R4.NMSFields; +import com.ticxo.modelengine.v1_20_R4.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public Iterable getArmorSlots() { + return this.armorItems; + } + + public ItemStack getItemBySlot(EquipmentSlot slot) { + return switch (slot.getType()) { + case HAND -> (ItemStack)this.handItems.get(slot.getIndex()); + case ARMOR -> (ItemStack)this.armorItems.get(slot.getIndex()); + case BODY -> ItemStack.EMPTY; + default -> throw new MatchException(null, null); + }; + } + + public void setItemSlot(EquipmentSlot slot, ItemStack stack) { + this.verifyEquippedItem(stack); + switch (slot.getType()) { + case HAND: + this.onEquipItem(slot, (ItemStack)this.handItems.set(slot.getIndex(), stack), stack); + break; + case ARMOR: + this.onEquipItem(slot, (ItemStack)this.armorItems.set(slot.getIndex(), stack), stack); + } + } + + public boolean isInvisible() { + return true; + } + + public void push(Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox() { + if (this.subHitbox == null) { + return super.makeBoundingBox(); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurt(DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurt(source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return this.bone.getActiveModel().getModeledEntity().getBase().hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, + entity, + new Vector(0, 0, 0), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact( + this, + player.getBukkitEntity(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND + ); + + return switch (result) { + case SUCCESS -> InteractionResult.SUCCESS; + case SUCCESS_NO_ITEM_USED -> InteractionResult.SUCCESS_NO_ITEM_USED; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.CONSUME_PARTIAL; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }; + } + } + + public boolean shouldBeSaved() { + return false; + } + + public CraftEntity getBukkitEntity() { + CraftEntity bukkitEntity = this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + CraftEntity var5 = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(var5); + return var5; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/hitbox/OBB.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/hitbox/OBB.java new file mode 100644 index 0000000..8ece746 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_20_R4.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..12c49d3 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_20_R4.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..900baec --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R4.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/GroundNavigationWrapper.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..bfb5b32 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R4.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..71f3597 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_20_R4.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..fed615e --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_20_R4.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/ModelEngineChannelHandler.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..6b44c89 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/ModelEngineChannelHandler.java @@ -0,0 +1,407 @@ +package com.ticxo.modelengine.v1_20_R4.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R4.NMSFields; +import com.ticxo.modelengine.v1_20_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_20_R4.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntList; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet rawPacket && asClientPacket(rawPacket) instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + Collection> post = this.writeInterceptors.acceptPost(result); + if (!post.isEmpty()) { + list.addAll(post); + } + } + } + + if (!list.isEmpty()) { + Packet var12 = new ClientboundBundlePacket(list); + super.write(ctx, var12, promise); + } + } else { + Packet var13 = this.writeInterceptors.accept(packet); + if (var13 == null) { + return; + } + + Collection> post = this.writeInterceptors.acceptPost(var13); + if (post.isEmpty()) { + super.write(ctx, var13, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var13); + list.addAll(post); + Packet var14 = new ClientboundBundlePacket(list); + super.write(ctx, var14, promise); + } + } + } catch (Throwable var11) { + var11.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List> handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List> handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + ArrayList> list = new ArrayList<>(); + model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT).ifPresent(behaviorRenderer -> { + if (behaviorRenderer instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + MountRenderer.Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + CollectionDataTracker ids = mount.getPassengers(); + list.add(new ClientboundSetPassengersPacket(EntityContainer.of(mount.getMountId(), ids))); + } + } + }); + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + IntList ids = packet.getEntityIds(); + + for (int i = 0; i < ids.size(); i++) { + this.markViewersDirty(ids.getInt(i)); + } + + int[] set = packet.getEntityIds().intStream().filter(id -> ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE).toArray(); + return set.length == packet.getEntityIds().size() ? packet : new ClientboundRemoveEntitiesPacket(IntArrayList.wrap(set)); + } + + private > T handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readClientbound(packet); + int id = buf.readVarInt(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private > T handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(packet.id()); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + buf.writeByte(255); + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + int id = packet.entityId(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + return !changed ? packet : new ClientboundSetPassengersPacket(EntityContainer.of(packet.getVehicle(), new IntArrayList(merged))); + } + } + } + + private Packet handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readServerbound(packet); + int entityId = buf.readVarInt(); + int action = buf.readVarInt(); + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), action, packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, action, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, action, packet) : packet); + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountController.MountInput input = controller.getInput(); + if (input == null) { + controller.setInput( + new MountController.MountInput(inputPacket.getXxa(), inputPacket.getZza(), inputPacket.isJumping(), inputPacket.isShiftKeyDown()) + ); + } else { + input.setSide(inputPacket.getXxa()); + input.setFront(inputPacket.getZza()); + input.setJump(inputPacket.isJumping()); + input.setSneak(inputPacket.isShiftKeyDown()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + return packet; + } + + @SuppressWarnings("unchecked") + private static Packet asClientPacket(Object packet) { + return (Packet)packet; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/NetworkHandlerImpl.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..3e429be --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/NetworkHandlerImpl.java @@ -0,0 +1,141 @@ +package com.ticxo.modelengine.v1_20_R4.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R4.NMSFields; +import com.ticxo.modelengine.v1_20_R4.network.utils.Bundler; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection> collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/patch/PatchedServerGamePacketListener.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..c1db318 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,419 @@ +package com.ticxo.modelengine.v1_20_R4.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_20_R4.NMSMethods; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(final ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().serverLevel()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.serverLevel(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + final ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + null + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + position + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + position + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + activeModel, + BaseEntityInteractEvent.Action.ATTACK, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, null); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, pos); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent( + craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND, null + ); + } + } + ); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= player.entityInteractionRange() * player.entityInteractionRange())) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelected().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + if (entity.tracker != null && player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + ServerEntity serverEntity = entity.tracker.serverEntity; + List> list = new ArrayList<>(); + serverEntity.sendPairingData(player, list::add); + player.connection.send(new ClientboundBundlePacket(list)); + } + + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem) { + List> data = entity.getEntityData().packAll(); + if (data != null && player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + player.connection.send(new ClientboundSetEntityDataPacket(entity.getId(), data)); + } + + if (entity instanceof Allay allay) { + List> equipment = Arrays.stream(EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.getItemBySlot(slot))) + .collect(Collectors.toList()); + connection.send(new ClientboundSetEquipmentPacket(entity.getId(), equipment)); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.serverLevel()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.serverLevel(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level().clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.isSameItemSameComponents(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand, + movingobjectpositionblock.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, itemstack, enumhand); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.resyncUsingItem(player); + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent( + CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacketWrapper packet, InteractionHand hand, @Nullable Vec3 vector + ) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.isAttack(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND, + vector != null ? new Vector(vector.x, vector.y, vector.z) : null + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..92b1d68 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,75 @@ +package com.ticxo.modelengine.v1_20_R4.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper implements Packet { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + private final boolean isAttack; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, int action, ServerboundInteractPacket original) { + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + this.isAttack = action == 1; + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_INTERACT; + } + + public int getEntityId() { + return this.originalId; + } + + public boolean isAttack() { + return this.isAttack; + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/BulkEntityDataEncoder.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..ccd6119 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_20_R4.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/Bundler.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/Bundler.java new file mode 100644 index 0000000..fc289ed --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_20_R4.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.getLast(); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection> packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.getLast(); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet packet : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/NetworkUtils.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/NetworkUtils.java new file mode 100644 index 0000000..911490c --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/NetworkUtils.java @@ -0,0 +1,336 @@ +package com.ticxo.modelengine.v1_20_R4.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_20_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_20_R4.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static final ProtocolInfo CLIENTBOUND_CODEC = GameProtocols.CLIENTBOUND + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + public static final ProtocolInfo SERVERBOUND_CODEC = GameProtocols.SERVERBOUND + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + private static final Map, Constructor> PACKET_CONSTRUCTOR = new HashMap<>(); + + public static FriendlyByteBuf createByteBuf() { + return new FriendlyByteBuf(Unpooled.buffer()); + } + + public static FriendlyByteBuf createByteBuf(Consumer consumer) { + FriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static > T create(Class clazz, FriendlyByteBuf buf) { + Constructor constructor = PACKET_CONSTRUCTOR.computeIfAbsent(clazz, aClass -> { + try { + Constructor c = aClass.getDeclaredConstructor(RegistryFriendlyByteBuf.class); + c.setAccessible(true); + return c; + } catch (NoSuchMethodException var4x) { + try { + Constructor cx = aClass.getDeclaredConstructor(FriendlyByteBuf.class); + cx.setAccessible(true); + return cx; + } catch (NoSuchMethodException var3) { + throw new RuntimeException(var3); + } + } + }); + + try { + return (T)constructor.newInstance(buf); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException var4) { + throw new RuntimeException(var4); + } + } + + public static FriendlyByteBuf readServerbound(Packet packet) { + FriendlyByteBuf buf = createByteBuf(); + SERVERBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static FriendlyByteBuf readClientbound(Packet packet) { + FriendlyByteBuf buf = createByteBuf(); + CLIENTBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createCameraPivotSpawn(int id, UUID uuid, Vector3f pos, float height) { + ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket( + id, uuid, pos.x, pos.y - height, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createCameraPivotTeleport(int id, Vector3f pos, float height) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - height, pos.z); + ClientboundTeleportEntityPacket packet = new ClientboundTeleportEntityPacket(container); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - 0.375, pos.z); + ClientboundTeleportEntityPacket tpHigher = new ClientboundTeleportEntityPacket(container); + container = EntityContainer.of(id); + container.setId(id); + container.setPosRaw(pos.x, pos.y - 0.5, pos.z); + ClientboundTeleportEntityPacket tpLower = new ClientboundTeleportEntityPacket(container); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Object createCameraPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos, float height) { + if (codec == null) { + return createCameraPivotTeleport(id, pos, height); + } else { + return switch (codec.update(pos.x, pos.y - height, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createCameraPivotTeleport(id, pos, height); + }; + } + } + + public static Packets.PacketSupplier lodWrapper( + ModeledEntity modeledEntity, BiFunction> packetFunction + ) { + return uuid -> { + AnimationLODHandler.LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/PacketInterceptor.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..aafadfd --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/PacketInterceptor.java @@ -0,0 +1,84 @@ +package com.ticxo.modelengine.v1_20_R4.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor

    { + private final Map>, PacketInterceptor

    .Modifier>> registry = Maps.newConcurrentMap(); + private final Map>, PacketInterceptor

    .Listener>> postRegistry = Maps.newConcurrentMap(); + + public > PacketInterceptor

    register(Class clazz, Function> function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public > PacketInterceptor

    registerPost(Class clazz, Function>> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor

    .Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection> acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor

    .Listener listener = this.postRegistry.get(original.getClass()); + return (Collection>)(listener != null ? listener.listen(original) : List.of()); + } + } + + class Listener> { + private final Class clazz; + private final Function>> function; + + public Collection> listen(Packet original) { + try { + Collection> collection = this.function.apply(this.clazz.cast(original)); + return (Collection>)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(final Class clazz, final Function>> function) { + this.clazz = clazz; + this.function = function; + } + } + + class Modifier> { + private final Class clazz; + private final Function> function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(final Class clazz, final Function> function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/Packets.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/Packets.java new file mode 100644 index 0000000..cc70f27 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_20_R4.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/HeldItemParser.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..d669ec4 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/HeldItemParser.java @@ -0,0 +1,180 @@ +package com.ticxo.modelengine.v1_20_R4.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_20_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapToInt(HeldItemRenderer.Item::getId)) + )) + ); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Map items = renderer.getRendered(); + IntArrayList entityIds = IntArrayList.toList(items.values().stream().mapToInt(HeldItemRenderer.Item::getId)); + entityIds.add(renderer.getId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + return new ClientboundSetEntityDataPacket(renderer.getId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, HeldItemRenderer.Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(HeldItemRenderer.Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(11); + if (spawn) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, this.viewRange)); + } else if (renderer.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + renderer.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), spawn); + renderer.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), spawn); + renderer.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + renderer.getModel() + .ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + renderer.getDisplay() + .ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), spawn); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(renderer.getId(), entityData); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location loc = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(loc.getX(), loc.getY(), loc.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + EntityContainer container = EntityContainer.of(renderer.getId()); + container.setPosRaw(loc.getX(), loc.getY(), loc.getZ()); + return new ClientboundTeleportEntityPacket(container); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getId(), renderer.getPassengers())); + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/LeashParser.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/LeashParser.java new file mode 100644 index 0000000..63f46a9 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/LeashParser.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.v1_20_R4.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Map leashes = renderer.getRendered(); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(IntArrayList.toList(leashes.values().stream().mapMultiToInt((leash, intConsumer) -> { + intConsumer.accept(leash.getLeashId()); + intConsumer.accept(leash.getPivotId()); + })))); + } + } + + private Packets.PacketSupplier pivotSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos); + } + + private ClientboundAddEntityPacket leashSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.SLIME, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetEntityDataPacket leashData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getLeashId(), EntityUtils.LEASH_SLIME_DATA); + } + + private ClientboundSetPassengersPacket mount(LeashRenderer.Leash renderer) { + ArrayList passengers = new ArrayList<>(1); + passengers.add(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), passengers)); + } + + private Object move(LeashRenderer.Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos); + } + } + + private ClientboundSetEntityLinkPacket link(LeashRenderer.Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(EntityContainer.of(renderer.getLeashId()), EntityContainer.of(renderer.getConnected().get())); + } + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/MountParser.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/MountParser.java new file mode 100644 index 0000000..c7f92f4 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/MountParser.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.v1_20_R4.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getMountId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Collection mounts = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(mounts.size() * 2); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getMountId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(MountRenderer.Mount renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket mountSpawn(MountRenderer.Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getMountId())); + } + + private ClientboundSetPassengersPacket mount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getMountId(), renderer.getPassengers())); + } + + private Packets.PacketSupplier pivotMove(MountRenderer.Mount renderer) { + return NetworkUtils.createPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(MountRenderer.Mount renderer) { + return new Rot(renderer.getMountId(), renderer.getYaw().get(), (byte)0, false); + } + + private ClientboundSetEntityDataPacket mountHealth(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, renderer.getHealth().get()))); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(MountRenderer.Mount renderer) { + AttributeInstance attributeInstance = new AttributeInstance(Attributes.MAX_HEALTH, onDirty -> {}); + attributeInstance.setBaseValue(renderer.getMaxHealth().get().floatValue()); + return new ClientboundUpdateAttributesPacket(renderer.getMountId(), Lists.newArrayList(new AttributeInstance[]{attributeInstance})); + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/NameTagParser.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..b41d258 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/NameTagParser.java @@ -0,0 +1,191 @@ +package com.ticxo.modelengine.v1_20_R4.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Component.Serializer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTagRenderer.NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTagRenderer.NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Collection nameTags = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(nameTags.size() * 2); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + List> entityData = List.of(); + if (spawn) { + entityData = EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA; + } + + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), entityData); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTagRenderer.NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + renderer.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + renderer.getTranslate().ifDirty(flag -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getScale().ifDirty(flag -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getTextOpacity().ifDirty(flag -> entityData.add(new DataValue(26, EntityDataSerializers.BYTE, flag)), spawn); + renderer.getBackgroundColor().ifDirty(flag -> entityData.add(new DataValue(25, EntityDataSerializers.INT, flag)), spawn); + renderer.getStyle().ifDirty(flags -> entityData.add(new DataValue(27, EntityDataSerializers.BYTE, flags)), spawn); + renderer.getLineWidth().ifDirty(flag -> entityData.add(new DataValue(24, EntityDataSerializers.INT, flag)), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new MatchException(null, null); + }; + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, value)); + }, spawn); + renderer.getJsonString() + .ifDirty( + jsonString -> { + if (jsonString == null) { + entityData.add(new DataValue(23, EntityDataSerializers.COMPONENT, Component.empty())); + } else { + entityData.add( + new DataValue(23, EntityDataSerializers.COMPONENT, Serializer.fromJson(jsonString, MinecraftServer.getServer().registryAccess())) + ); + } + }, + spawn + ); + renderer.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getTagId(), entityData); + } + } + + private Object pivotMove(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTagRenderer.NameTag renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getTagId())); + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/SegmentParser.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..cf6a499 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/SegmentParser.java @@ -0,0 +1,205 @@ +package com.ticxo.modelengine.v1_20_R4.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (SegmentRenderer.Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + IntArrayList destroy = new IntArrayList(); + + for (SegmentRenderer.Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(destroy))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(SegmentRenderer.Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SegmentRenderer.Pivot pivot) { + return new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(SegmentRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(SegmentRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(SegmentRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + ArrayList> entityData = new ArrayList<>(13); + if (force) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } else if (bone.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : 1)), force); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), force); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/SubHitboxParser.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..891a564 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/behavior/SubHitboxParser.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_20_R4.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitboxRenderer.SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Collection subHitboxes = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(subHitboxes.size() * 2); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private Object pivotMove(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getHitboxId())); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitboxRenderer.SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitboxRenderer.SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(4); + renderer.getWidth().ifDirty(width -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, width)), spawn); + renderer.getHeight().ifDirty(height -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, height)), spawn); + renderer.clearDirty(); + return new ClientboundSetEntityDataPacket(renderer.getHitboxId(), entityData); + } + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/model/DisplayParser.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/model/DisplayParser.java new file mode 100644 index 0000000..2062090 --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/model/DisplayParser.java @@ -0,0 +1,789 @@ +package com.ticxo.modelengine.v1_20_R4.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_20_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static StreamCodec CUSTOM_PAYLOAD_CODEC; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + if (renderer.hasGlowAudience()) { + this.updateAudienceGlow(renderer, data.getTracking().keySet(), data.getStartTracking(), this.noCullForcePlayers); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + private void updateAudienceGlow(DisplayRenderer renderer, Set current, Set startTracking, Set forceUpdates) { + for (DisplayBone bone : renderer.getRendered().values()) { + Set audience = bone.getGlowAudience().get(); + if (audience != null) { + boolean changed = bone.isAudienceGlowDirty(); + if (changed || !startTracking.isEmpty() || !forceUpdates.isEmpty()) { + boolean glowing = bone.getAudienceGlowing().get(); + int color = bone.getAudienceGlowColor().get(); + Set on = new HashSet<>(); + Set off = new HashSet<>(); + if (changed) { + for (UUID uuid : current) { + if (glowing && audience.contains(uuid)) { + on.add(uuid); + } else { + off.add(uuid); + } + } + + bone.clearAudienceGlowDirty(); + } else if (glowing) { + for (UUID uuidx : startTracking) { + if (audience.contains(uuidx)) { + on.add(uuidx); + } + } + + for (UUID uuidxx : forceUpdates) { + if (audience.contains(uuidxx)) { + on.add(uuidxx); + } + } + } + + if (!on.isEmpty() || !off.isEmpty()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + int id = boneData.getId(); + if (!on.isEmpty()) { + NetworkUtils.send(on, this.audienceGlowData(id, true, color)); + } + + if (!off.isEmpty()) { + NetworkUtils.send(off, this.audienceGlowData(id, false, color)); + } + } + } + } + } + } + } + + private ClientboundSetEntityDataPacket audienceGlowData(int entityId, boolean glowing, int color) { + ArrayList> entityData = new ArrayList<>(2); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(glowing ? 96 : 32))); + if (glowing) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + + return new ClientboundSetEntityDataPacket(entityId, entityData); + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + set.add((Packet)this.pivotCameraResize(pivot)); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(destroy)))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(hitboxDestroy)))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)(u -> this.displayData(u, null, boneData, false, transformOnly))); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + AnimationLODHandler.LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(FriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CODEC == null) { + Field field = ClientboundCustomPayloadPacket.class.getField("GAMEPLAY_STREAM_CODEC"); + field.setAccessible(true); + CUSTOM_PAYLOAD_CODEC = (StreamCodec)field.get(null); + } + + return (Packet)CUSTOM_PAYLOAD_CODEC.decode(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData( + BulkEntityDataEncoder encoder, + UUID uuid, + @Nullable AnimationLODHandler.LODTracker tracker, + DisplayBone.BoneData boneData, + boolean force, + boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? new ClientboundSetEntityDataPacket(pivot.getId(), this.cameraPivotData(pivot.getCameraHeight().get())) + : new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private List> cameraPivotData(float height) { + return List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(8, EntityDataSerializers.FLOAT, 0.0F), + new DataValue(9, EntityDataSerializers.FLOAT, height) + ); + } + + private ClientboundSetPassengersPacket pivotMount(DisplayRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(DisplayRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundSetEntityDataPacket pivotCameraResize(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() && pivot.getCameraHeight().isDirty() + ? new ClientboundSetEntityDataPacket(pivot.getId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, pivot.getCameraHeight().get()))) + : null; + } + + private ClientboundAddEntityPacket displaySpawn(DisplayRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData( + UUID uuid, @Nullable AnimationLODHandler.LODTracker tracker, DisplayBone.BoneData boneData, boolean force, boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + ArrayList> entityData = new ArrayList<>(13); + if (!force && update != 0) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : lodTick)), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + entityData.add(new DataValue(16, EntityDataSerializers.INT, val)); + } + }, force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + } + }, force); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + + private ClientboundSetEntityDataPacket displayVisibleData(DisplayBone.BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)))); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color))); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val))); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F))); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)))); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()))); + this.cleanupQueue.add(bone::clearDirty); + return new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(DisplayRenderer.Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(DisplayRenderer.Hitbox hitbox) { + return !hitbox.isPivotVisible() ? null : new ClientboundSetEntityDataPacket(hitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket hitboxSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(4); + hitbox.getWidth().ifDirty(val -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, val)), spawn); + hitbox.getHeight().ifDirty(val -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, val)), spawn); + return new ClientboundSetEntityDataPacket(hitbox.getHitboxId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(2); + hitbox.getShadowRadius().ifDirty(val -> entityData.add(new DataValue(18, EntityDataSerializers.FLOAT, val)), spawn); + return new ClientboundSetEntityDataPacket(hitbox.getShadowId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(DisplayRenderer.Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(DisplayRenderer.Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + return new ClientboundSetPassengersPacket(EntityContainer.of(hitbox.getPivotId(), passengers)); + } + } +} diff --git a/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/vfx/VFXDisplayParser.java b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..5b7c8bf --- /dev/null +++ b/nms/v1_20_R4/src/main/java/com/ticxo/modelengine/v1_20_R4/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,131 @@ +package com.ticxo.modelengine.v1_20_R4.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_20_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_20_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_20_R4.network.utils.Packets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(new int[]{vfx.getPivotId(), vfx.getModelId()})); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXDisplayRenderer.VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetEntityDataPacket(vfx.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXDisplayRenderer.VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXDisplayRenderer.VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(9); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getModelId()); + if (spawn) { + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)32)); + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, 4096.0F)); + entityData.add(new DataValue(24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal())); + } else if (vfx.isModelDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + vfx.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + vfx.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + vfx.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + vfx.clearModelDirty(); + return new ClientboundSetEntityDataPacket(vfx.getModelId(), entityData); + } + } + + private Object teleport(VFXDisplayRenderer.VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXDisplayRenderer.VFXModel vfx) { + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeVarInt(vfx.getPivotId()); + buf.writeVarInt(1); + buf.writeVarInt(vfx.getModelId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(vfx.getPivotId(), vfx.getModelId())); + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSFields.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSFields.java new file mode 100644 index 0000000..c1c6dc2 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSFields.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_21_R1; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionUtils.ReflectionEnum { + ENTITY_dimensions(Entity.class, "bd", "dimensions"), + ENTITY_eyeHeight(Entity.class, "be", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "ch", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "bn", "jumping"), + MOB_lookControl(Mob.class, "bS", "lookControl"), + MOB_moveControl(Mob.class, "bT", "moveControl"), + MOB_navigation(Mob.class, "bV", "navigation"), + MOB_goalSelector(Mob.class, "bW", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "cd", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "I", "clientIsFloating"), + SERVER_COMMON_PACKET_LISTENER_IMPL_connection(ServerCommonPacketListenerImpl.class, "e", "connection"), + MOVE_CONTROL_operation(MoveControl.class, "k", "operation"), + TRACKED_ENTITY_serverEntity(TrackedEntity.class, "b", "serverEntity"), + TRACKED_ENTITY_range(TrackedEntity.class, "d", "range"), + LEVEL_threadSafeRandom(Level.class, "f", "threadSafeRandom"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "a", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "b", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(final Class target, final String obfuscated, final String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSHandler_v1_21_R1.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSHandler_v1_21_R1.java new file mode 100644 index 0000000..f7c1b56 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSHandler_v1_21_R1.java @@ -0,0 +1,179 @@ +package com.ticxo.modelengine.v1_21_R1; + +import com.mojang.math.MatrixUtil; +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.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R1.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_21_R1.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R1.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_21_R1.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_21_R1.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_21_R1.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_21_R1.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_21_R1.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_21_R1.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.entity.Entity; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_21_R1 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + FriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, NetworkUtils.create(ClientboundSetPassengersPacket.class, byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(EntityContainer.of(mountId, passengerIds)); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSMethods.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSMethods.java new file mode 100644 index 0000000..396eac1 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/NMSMethods.java @@ -0,0 +1,48 @@ +package com.ticxo.modelengine.v1_21_R1; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements ReflectionUtils.MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "i", "getInstrument", ItemStack.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityContainer.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityContainer.java new file mode 100644 index 0000000..b5dc01a --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityContainer.java @@ -0,0 +1,52 @@ +package com.ticxo.modelengine.v1_21_R1.entity; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.syncher.SynchedEntityData.Builder; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.ApiStatus.Internal; + +@Internal +public class EntityContainer extends Entity { + public static EntityContainer of(int id) { + return new EntityContainer(id); + } + + public static Entity of(int id, int... passengerIds) { + EntityContainer container = of(id); + container.setPassengers(Arrays.stream(passengerIds).mapToObj(EntityContainer::new).toList()); + return container; + } + + public static Entity of(int id, Collection passengerIds) { + EntityContainer container = of(id); + container.setPassengers(passengerIds.stream().map(EntityContainer::new).toList()); + return container; + } + + private EntityContainer(int id) { + super(EntityType.INTERACTION, null); + this.setId(id); + this.setPosRaw(0.0, 0.0, 0.0); + this.setRot(0.0F, 0.0F); + this.setOnGround(false); + } + + protected void setPassengers(List passengers) { + this.passengers = ImmutableList.copyOf(passengers); + } + + protected void defineSynchedData(@NotNull Builder builder) { + } + + protected void readAdditionalSaveData(@NotNull CompoundTag nbt) { + } + + protected void addAdditionalSaveData(@NotNull CompoundTag nbt) { + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityHandlerImpl.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..b01af26 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityHandlerImpl.java @@ -0,0 +1,731 @@ +package com.ticxo.modelengine.v1_21_R1.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_21_R1.NMSFields; +import com.ticxo.modelengine.v1_21_R1.NMSMethods; +import com.ticxo.modelengine.v1_21_R1.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_21_R1.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_21_R1.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_21_R1.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_21_R1.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_21_R1.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_21_R1.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R1.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_21_R1.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R1.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.minecraft.core.Holder; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityAttachments; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.UseAnim; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + float width = (float)hitbox.getMaxWidth(); + float height = (float)hitbox.getHeight(); + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions(width, height, (float)hitbox.getEyeHeight(), EntityAttachments.createDefault(width, height), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + if (EntityUtils.nms(entity) instanceof LivingEntity living) { + living.getAttributes().registerAttribute(Attributes.STEP_HEIGHT); + Objects.requireNonNull(living.getAttribute(Attributes.STEP_HEIGHT)).setBaseValue(height); + } + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityType.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y - nmsEntity.getVehicleAttachmentPoint(this.dummyArmorStand).y; + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + entity.getEntityId(), List.of(new DataValue(0, EntityDataSerializers.BYTE, data)) + ); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + switch (oldNav) { + case WallClimberNavigation wallClimberNavigation: + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + break; + case GroundPathNavigation groundPathNavigation: + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + break; + case FlyingPathNavigation flyingPathNavigation: + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + break; + case WaterBoundPathNavigation waterBoundPathNavigation: + newNav = new WaterBoundNavigationWrapper(mob); + break; + case AmphibiousPathNavigation amphibiousPathNavigation: + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + break; + default: + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var13) { + var13.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + ServerLevel level = ((CraftWorld)location.getWorld()).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + return EntityUtils.nms(entity).hurt(damageSource, amount); + } else { + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + } + + @Override + public EntityHandler.InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case SUCCESS -> EntityHandler.InteractionResult.SUCCESS; + case SUCCESS_NO_ITEM_USED -> EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED; + case CONSUME -> EntityHandler.InteractionResult.CONSUME; + case CONSUME_PARTIAL -> EntityHandler.InteractionResult.CONSUME_PARTIAL; + case PASS -> EntityHandler.InteractionResult.PASS; + case FAIL -> EntityHandler.InteractionResult.FAIL; + default -> throw new MatchException(null, null); + }; + } else { + return EntityHandler.InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket( + DynamicHitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA + ); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(DynamicHitbox.getHitboxId(), EntityUtils.DEFAULT_SLIME_DATA); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket( + EntityContainer.of(DynamicHitbox.getPivotId(), DynamicHitbox.getHitboxId()) + ); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0, 0.0F, 0.0F + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != UseAnim.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + player.getEntityId(), List.of(new DataValue(8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3))) + ); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call( + instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack, nmsPlayer.registryAccess() + ); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public Float getCameraEyeHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return nmsEntity.getDimensions(Pose.STANDING).eyeHeight(); + } + + @Override + public Float getCameraPivotHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + EntityDimensions dimensions = nmsEntity.getDimensions(nmsEntity.getPose()); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 attachment = ReflectionUtils.call(nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, dimensions, 1.0F); + return attachment == null ? null : (float)(dimensions.eyeHeight() - attachment.y); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = level.getChunkSource().chunkMap.entityMap; + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = lvl.getChunkSource().chunkMap.entityMap; + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3D(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + EntityHandler.BoxRelToCam relX = EntityHandler.BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + EntityHandler.BoxRelToCam relY = EntityHandler.BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + EntityHandler.BoxRelToCam relZ = EntityHandler.BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == EntityHandler.BoxRelToCam.INSIDE && relY == EntityHandler.BoxRelToCam.INSIDE && relZ == EntityHandler.BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.DUST, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityMetadataID.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityMetadataID.java new file mode 100644 index 0000000..5a6d103 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityMetadataID.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.v1_21_R1.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityUtils.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityUtils.java new file mode 100644 index 0000000..9681b91 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/EntityUtils.java @@ -0,0 +1,30 @@ +package com.ticxo.modelengine.v1_21_R1.entity; + +import java.util.List; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.entity.CraftEntity; + +public class EntityUtils { + public static final List> DEFAULT_AREA_EFFECT_CLOUD_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(8, EntityDataSerializers.FLOAT, 0.0F) + ); + public static final List> DEFAULT_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(16, EntityDataSerializers.INT, 2) + ); + public static final List> DEFAULT_BAT_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE) + ); + public static final List> DEFAULT_ARMOR_STAND_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(15, EntityDataSerializers.BYTE, (byte)16) + ); + + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/OcclusionClipContext.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/OcclusionClipContext.java new file mode 100644 index 0000000..374c2d5 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v1_21_R1.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape(world, pos) == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (tX > 1.0 && tY > 1.0 && tZ > 1.0) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/TrackedEntityImpl.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..ecfcd7a --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/TrackedEntityImpl.java @@ -0,0 +1,286 @@ +package com.ticxo.modelengine.v1_21_R1.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R1.NMSFields; +import com.ticxo.modelengine.v1_21_R1.NMSMethods; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } + + @Override + public boolean isViewerSetUnchanged() { + if ((!this.mayHaveForced || this.forcedPairing.isEmpty() && this.forcedRemove.isEmpty()) && this.playerPredicate == DEFAULT_PREDICATE) { + if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } else { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/BodyRotationControlWrapper.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..77fd259 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_21_R1.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/LookControlWrapper.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..c2997ee --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/LookControlWrapper.java @@ -0,0 +1,143 @@ +package com.ticxo.modelengine.v1_21_R1.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; +import org.spigotmc.ActivationRange; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/MoveControlWrapper.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..6aba3c2 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/controller/MoveControlWrapper.java @@ -0,0 +1,246 @@ +package com.ticxo.modelengine.v1_21_R1.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R1.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + controller.setInput(new MountController.MountInput()); + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/hitbox/HitboxEntityImpl.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..0087166 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,305 @@ +package com.ticxo.modelengine.v1_21_R1.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_21_R1.NMSFields; +import com.ticxo.modelengine.v1_21_R1.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + public boolean canBeHitByProjectile() { + return this.subHitbox.isCanBeHitByProjectile(); + } + + @NotNull + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + @NotNull + public Iterable getArmorSlots() { + return this.armorItems; + } + + @NotNull + public ItemStack getItemBySlot(EquipmentSlot slot) { + return switch (slot.getType()) { + case HAND -> (ItemStack)this.handItems.get(slot.getIndex()); + case HUMANOID_ARMOR -> (ItemStack)this.armorItems.get(slot.getIndex()); + case ANIMAL_ARMOR -> ItemStack.EMPTY; + default -> throw new MatchException(null, null); + }; + } + + public void setItemSlot(EquipmentSlot slot, @NotNull ItemStack stack) { + this.verifyEquippedItem(stack); + switch (slot.getType()) { + case HAND: + this.onEquipItem(slot, (ItemStack)this.handItems.set(slot.getIndex(), stack), stack); + break; + case HUMANOID_ARMOR: + this.onEquipItem(slot, (ItemStack)this.armorItems.set(slot.getIndex(), stack), stack); + } + } + + public boolean isInvisible() { + return true; + } + + public void push(@NotNull Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox() { + if (this.subHitbox == null) { + return super.makeBoundingBox(); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(@NotNull Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurt(@NotNull DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurt(source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return this.bone.getActiveModel().getModeledEntity().getBase().hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, @NotNull InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, + entity, + new Vector(0, 0, 0), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact( + this, + player.getBukkitEntity(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND + ); + + return switch (result) { + case SUCCESS -> InteractionResult.SUCCESS; + case SUCCESS_NO_ITEM_USED -> InteractionResult.SUCCESS_NO_ITEM_USED; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.CONSUME_PARTIAL; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }; + } + } + + public boolean shouldBeSaved() { + return false; + } + + @NotNull + public CraftEntity getBukkitEntity() { + CraftEntity bukkitEntity = this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + CraftEntity var5 = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(var5); + return var5; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(@NotNull RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/hitbox/OBB.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/hitbox/OBB.java new file mode 100644 index 0000000..88a20ec --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R1.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..99d8701 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..030de1b --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/GroundNavigationWrapper.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..a7b709f --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..7004778 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..759b9d2 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_21_R1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/ModelEngineChannelHandler.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..0903ec4 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/ModelEngineChannelHandler.java @@ -0,0 +1,426 @@ +package com.ticxo.modelengine.v1_21_R1.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R1.NMSFields; +import com.ticxo.modelengine.v1_21_R1.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R1.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntList; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet rawPacket && asClientPacket(rawPacket) instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + Collection> post = this.writeInterceptors.acceptPost(result); + if (!post.isEmpty()) { + list.addAll(post); + } + } + } + + if (!list.isEmpty()) { + Packet var12 = new ClientboundBundlePacket(list); + super.write(ctx, var12, promise); + } + } else { + Packet var13 = this.writeInterceptors.accept(packet); + if (var13 == null) { + return; + } + + Collection> post = this.writeInterceptors.acceptPost(var13); + if (post.isEmpty()) { + super.write(ctx, var13, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var13); + list.addAll(post); + Packet var14 = new ClientboundBundlePacket(list); + super.write(ctx, var14, promise); + } + } + } catch (Throwable var11) { + var11.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List> handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List> handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + List> list = null; + Optional maybeMount = model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT); + if (maybeMount.isPresent() && maybeMount.get() instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + MountRenderer.Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + if (mount == null) { + return null; + } + + CollectionDataTracker ids = mount.getPassengers(); + list = new ArrayList<>(); + list.add(new ClientboundSetPassengersPacket(EntityContainer.of(mount.getMountId(), ids))); + } + } + + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + IntList ids = packet.getEntityIds(); + + for (int i = 0; i < ids.size(); i++) { + this.markViewersDirty(ids.getInt(i)); + } + + int[] set = packet.getEntityIds().intStream().filter(id -> ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE).toArray(); + return set.length == packet.getEntityIds().size() ? packet : new ClientboundRemoveEntitiesPacket(IntArrayList.wrap(set)); + } + + private > T handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readClientbound(packet); + + Packet var4; + try { + int id = buf.readVarInt(); + var4 = ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } finally { + buf.release(); + } + + return (T)var4; + } + + private > T handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + int id = packet.entityId(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + return !changed ? packet : new ClientboundSetPassengersPacket(EntityContainer.of(packet.getVehicle(), new IntArrayList(merged))); + } + } + } + + private Packet handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readServerbound(packet); + + int entityId; + int action; + try { + entityId = buf.readVarInt(); + action = buf.readVarInt(); + } finally { + buf.release(); + } + + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), action, packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, action, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, action, packet) : packet); + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountController.MountInput input = controller.getInput(); + if (input == null) { + controller.setInput( + new MountController.MountInput(inputPacket.getXxa(), inputPacket.getZza(), inputPacket.isJumping(), inputPacket.isShiftKeyDown()) + ); + } else { + input.setSide(inputPacket.getXxa()); + input.setFront(inputPacket.getZza()); + input.setJump(inputPacket.isJumping()); + input.setSneak(inputPacket.isShiftKeyDown()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + return packet; + } + + @SuppressWarnings("unchecked") + private static Packet asClientPacket(Object packet) { + return (Packet)packet; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/NetworkHandlerImpl.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..1bd491d --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/NetworkHandlerImpl.java @@ -0,0 +1,141 @@ +package com.ticxo.modelengine.v1_21_R1.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R1.NMSFields; +import com.ticxo.modelengine.v1_21_R1.network.utils.Bundler; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection> collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/patch/PatchedServerGamePacketListener.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..1ddb5ee --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,437 @@ +package com.ticxo.modelengine.v1_21_R1.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R1.NMSMethods; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(final ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().serverLevel()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.serverLevel(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + ModelBone hitBone = null; + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel == null) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(interactPacket.getRelayedId()); + if (hitbox != null) { + hitBone = hitbox.getBone(); + activeModel = hitBone.getActiveModel(); + } + } + + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + final ActiveModel finalActiveModel = activeModel; + final ModelBone finalHitBone = hitBone; + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + null, + finalHitBone + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + position, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + position, + finalHitBone + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.ATTACK, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, null); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, pos); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent( + craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND, null + ); + } + } + ); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= player.entityInteractionRange() * player.entityInteractionRange())) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelected().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + if (player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + ServerEntity serverEntity = entity.moonrise$getTrackedEntity().serverEntity; + List> list = new ArrayList<>(); + serverEntity.sendPairingData(player, list::add); + player.connection.send(new ClientboundBundlePacket(list)); + } + + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem) { + List> data = entity.getEntityData().packAll(); + if (data != null && player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + player.connection.send(new ClientboundSetEntityDataPacket(entity.getId(), data)); + } + + if (entity instanceof Allay allay) { + List> equipment = Arrays.stream(EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.getItemBySlot(slot))) + .collect(Collectors.toList()); + connection.send(new ClientboundSetEquipmentPacket(entity.getId(), equipment)); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.serverLevel()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.serverLevel(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level().clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.isSameItemSameComponents(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand, + movingobjectpositionblock.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, itemstack, enumhand); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.resyncUsingItem(player); + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult.shouldSwing()) { + player.swing(enumhand, true); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent( + CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacketWrapper packet, InteractionHand hand, @Nullable Vec3 vector + ) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.isAttack(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND, + vector != null ? new Vector(vector.x, vector.y, vector.z) : null + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..fde38d3 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,75 @@ +package com.ticxo.modelengine.v1_21_R1.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper implements Packet { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + private final boolean isAttack; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, int action, ServerboundInteractPacket original) { + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + this.isAttack = action == 1; + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_INTERACT; + } + + public int getEntityId() { + return this.originalId; + } + + public boolean isAttack() { + return this.isAttack; + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/BulkEntityDataEncoder.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..374e836 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R1.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/Bundler.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/Bundler.java new file mode 100644 index 0000000..7c33add --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_21_R1.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.getLast(); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection> packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.getLast(); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet packet : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/NetworkUtils.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/NetworkUtils.java new file mode 100644 index 0000000..f1e3cda --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/NetworkUtils.java @@ -0,0 +1,336 @@ +package com.ticxo.modelengine.v1_21_R1.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R1.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R1.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static final ProtocolInfo CLIENTBOUND_CODEC = GameProtocols.CLIENTBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + public static final ProtocolInfo SERVERBOUND_CODEC = GameProtocols.SERVERBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + private static final Map, Constructor> PACKET_CONSTRUCTOR = new HashMap<>(); + + public static FriendlyByteBuf createByteBuf() { + return new FriendlyByteBuf(Unpooled.buffer()); + } + + public static FriendlyByteBuf createByteBuf(Consumer consumer) { + FriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static > T create(Class clazz, FriendlyByteBuf buf) { + Constructor constructor = PACKET_CONSTRUCTOR.computeIfAbsent(clazz, aClass -> { + try { + Constructor c = aClass.getDeclaredConstructor(RegistryFriendlyByteBuf.class); + c.setAccessible(true); + return c; + } catch (NoSuchMethodException var4x) { + try { + Constructor cx = aClass.getDeclaredConstructor(FriendlyByteBuf.class); + cx.setAccessible(true); + return cx; + } catch (NoSuchMethodException var3) { + throw new RuntimeException(var3); + } + } + }); + + try { + return (T)constructor.newInstance(buf); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException var4) { + throw new RuntimeException(var4); + } + } + + public static FriendlyByteBuf readServerbound(Packet packet) { + FriendlyByteBuf buf = createByteBuf(); + SERVERBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static FriendlyByteBuf readClientbound(Packet packet) { + FriendlyByteBuf buf = createByteBuf(); + CLIENTBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createCameraPivotSpawn(int id, UUID uuid, Vector3f pos, float height) { + ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket( + id, uuid, pos.x, pos.y - height, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createCameraPivotTeleport(int id, Vector3f pos, float height) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - height, pos.z); + ClientboundTeleportEntityPacket packet = new ClientboundTeleportEntityPacket(container); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - 0.375, pos.z); + ClientboundTeleportEntityPacket tpHigher = new ClientboundTeleportEntityPacket(container); + container = EntityContainer.of(id); + container.setId(id); + container.setPosRaw(pos.x, pos.y - 0.5, pos.z); + ClientboundTeleportEntityPacket tpLower = new ClientboundTeleportEntityPacket(container); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Object createCameraPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos, float height) { + if (codec == null) { + return createCameraPivotTeleport(id, pos, height); + } else { + return switch (codec.update(pos.x, pos.y - height, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createCameraPivotTeleport(id, pos, height); + }; + } + } + + public static Packets.PacketSupplier lodWrapper( + ModeledEntity modeledEntity, BiFunction> packetFunction + ) { + return uuid -> { + AnimationLODHandler.LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/PacketInterceptor.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..fa52ab2 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/PacketInterceptor.java @@ -0,0 +1,84 @@ +package com.ticxo.modelengine.v1_21_R1.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor

    { + private final Map>, PacketInterceptor

    .Modifier>> registry = Maps.newConcurrentMap(); + private final Map>, PacketInterceptor

    .Listener>> postRegistry = Maps.newConcurrentMap(); + + public > PacketInterceptor

    register(Class clazz, Function> function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public > PacketInterceptor

    registerPost(Class clazz, Function>> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor

    .Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection> acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor

    .Listener listener = this.postRegistry.get(original.getClass()); + return (Collection>)(listener != null ? listener.listen(original) : List.of()); + } + } + + class Listener> { + private final Class clazz; + private final Function>> function; + + public Collection> listen(Packet original) { + try { + Collection> collection = this.function.apply(this.clazz.cast(original)); + return (Collection>)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(final Class clazz, final Function>> function) { + this.clazz = clazz; + this.function = function; + } + } + + class Modifier> { + private final Class clazz; + private final Function> function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(final Class clazz, final Function> function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/Packets.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/Packets.java new file mode 100644 index 0000000..db84035 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_21_R1.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/HeldItemParser.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..5318f11 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/HeldItemParser.java @@ -0,0 +1,180 @@ +package com.ticxo.modelengine.v1_21_R1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R1.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapToInt(HeldItemRenderer.Item::getId)) + )) + ); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Map items = renderer.getRendered(); + IntArrayList entityIds = IntArrayList.toList(items.values().stream().mapToInt(HeldItemRenderer.Item::getId)); + entityIds.add(renderer.getId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + return new ClientboundSetEntityDataPacket(renderer.getId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, HeldItemRenderer.Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(HeldItemRenderer.Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(11); + if (spawn) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, this.viewRange)); + } else if (renderer.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + renderer.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), spawn); + renderer.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), spawn); + renderer.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + renderer.getModel() + .ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + renderer.getDisplay() + .ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getId(), entityData); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location loc = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(loc.getX(), loc.getY(), loc.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + EntityContainer container = EntityContainer.of(renderer.getId()); + container.setPosRaw(loc.getX(), loc.getY(), loc.getZ()); + return new ClientboundTeleportEntityPacket(container); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getId(), renderer.getPassengers())); + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/LeashParser.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/LeashParser.java new file mode 100644 index 0000000..0a10915 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/LeashParser.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.v1_21_R1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Map leashes = renderer.getRendered(); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(IntArrayList.toList(leashes.values().stream().mapMultiToInt((leash, intConsumer) -> { + intConsumer.accept(leash.getLeashId()); + intConsumer.accept(leash.getPivotId()); + })))); + } + } + + private Packets.PacketSupplier pivotSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + + private ClientboundAddEntityPacket leashSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y - 0.45, pos.z - 0.2, 0.0F, 0.0F, EntityType.BAT, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetEntityDataPacket leashData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getLeashId(), EntityUtils.DEFAULT_BAT_DATA); + } + + private ClientboundSetPassengersPacket mount(LeashRenderer.Leash renderer) { + ArrayList passengers = new ArrayList<>(1); + passengers.add(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), passengers)); + } + + private Object move(LeashRenderer.Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + } + + private ClientboundSetEntityLinkPacket link(LeashRenderer.Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(EntityContainer.of(renderer.getLeashId()), EntityContainer.of(renderer.getConnected().get())); + } + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/MountParser.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/MountParser.java new file mode 100644 index 0000000..196c4f7 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/MountParser.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.v1_21_R1.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R1.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getMountId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Collection mounts = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(mounts.size() * 2); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getMountId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(MountRenderer.Mount renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket mountSpawn(MountRenderer.Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getMountId())); + } + + private ClientboundSetPassengersPacket mount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getMountId(), renderer.getPassengers())); + } + + private Packets.PacketSupplier pivotMove(MountRenderer.Mount renderer) { + return NetworkUtils.createPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(MountRenderer.Mount renderer) { + return new Rot(renderer.getMountId(), renderer.getYaw().get(), (byte)0, false); + } + + private ClientboundSetEntityDataPacket mountHealth(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, renderer.getHealth().get()))); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(MountRenderer.Mount renderer) { + AttributeInstance attributeInstance = new AttributeInstance(Attributes.MAX_HEALTH, onDirty -> {}); + attributeInstance.setBaseValue(renderer.getMaxHealth().get().floatValue()); + return new ClientboundUpdateAttributesPacket(renderer.getMountId(), Lists.newArrayList(new AttributeInstance[]{attributeInstance})); + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/NameTagParser.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..809ff67 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/NameTagParser.java @@ -0,0 +1,184 @@ +package com.ticxo.modelengine.v1_21_R1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Component.Serializer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTagRenderer.NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTagRenderer.NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Collection nameTags = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(nameTags.size() * 2); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + return !spawn ? null : new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTagRenderer.NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(7); + renderer.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + renderer.getTranslate().ifDirty(flag -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getScale().ifDirty(flag -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getTextOpacity().ifDirty(flag -> entityData.add(new DataValue(26, EntityDataSerializers.BYTE, flag)), spawn); + renderer.getBackgroundColor().ifDirty(flag -> entityData.add(new DataValue(25, EntityDataSerializers.INT, flag)), spawn); + renderer.getStyle().ifDirty(flags -> entityData.add(new DataValue(27, EntityDataSerializers.BYTE, flags)), spawn); + renderer.getLineWidth().ifDirty(flag -> entityData.add(new DataValue(24, EntityDataSerializers.INT, flag)), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new MatchException(null, null); + }; + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, value)); + }, spawn); + renderer.getJsonString() + .ifDirty( + jsonString -> { + if (jsonString == null) { + entityData.add(new DataValue(23, EntityDataSerializers.COMPONENT, Component.empty())); + } else { + entityData.add( + new DataValue(23, EntityDataSerializers.COMPONENT, Serializer.fromJson(jsonString, MinecraftServer.getServer().registryAccess())) + ); + } + }, + spawn + ); + renderer.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getTagId(), entityData); + } + } + + private Object pivotMove(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTagRenderer.NameTag renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getTagId())); + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/SegmentParser.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..74124fe --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/SegmentParser.java @@ -0,0 +1,205 @@ +package com.ticxo.modelengine.v1_21_R1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R1.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (SegmentRenderer.Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + IntArrayList destroy = new IntArrayList(); + + for (SegmentRenderer.Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(destroy))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(SegmentRenderer.Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SegmentRenderer.Pivot pivot) { + return new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(SegmentRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(SegmentRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(SegmentRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + ArrayList> entityData = new ArrayList<>(13); + if (force) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } else if (bone.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : 1)), force); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), force); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/SubHitboxParser.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..43717c4 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/behavior/SubHitboxParser.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R1.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitboxRenderer.SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Collection subHitboxes = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(subHitboxes.size() * 2); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private Object pivotMove(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getHitboxId())); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitboxRenderer.SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitboxRenderer.SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(4); + renderer.getWidth().ifDirty(width -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, width)), spawn); + renderer.getHeight().ifDirty(height -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, height)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getHitboxId(), entityData); + } + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/model/DisplayParser.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/model/DisplayParser.java new file mode 100644 index 0000000..85ebe33 --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/model/DisplayParser.java @@ -0,0 +1,789 @@ +package com.ticxo.modelengine.v1_21_R1.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R1.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static StreamCodec CUSTOM_PAYLOAD_CODEC; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + if (renderer.hasGlowAudience()) { + this.updateAudienceGlow(renderer, data.getTracking().keySet(), data.getStartTracking(), this.noCullForcePlayers); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + private void updateAudienceGlow(DisplayRenderer renderer, Set current, Set startTracking, Set forceUpdates) { + for (DisplayBone bone : renderer.getRendered().values()) { + Set audience = bone.getGlowAudience().get(); + if (audience != null) { + boolean changed = bone.isAudienceGlowDirty(); + if (changed || !startTracking.isEmpty() || !forceUpdates.isEmpty()) { + boolean glowing = bone.getAudienceGlowing().get(); + int color = bone.getAudienceGlowColor().get(); + Set on = new HashSet<>(); + Set off = new HashSet<>(); + if (changed) { + for (UUID uuid : current) { + if (glowing && audience.contains(uuid)) { + on.add(uuid); + } else { + off.add(uuid); + } + } + + bone.clearAudienceGlowDirty(); + } else if (glowing) { + for (UUID uuidx : startTracking) { + if (audience.contains(uuidx)) { + on.add(uuidx); + } + } + + for (UUID uuidxx : forceUpdates) { + if (audience.contains(uuidxx)) { + on.add(uuidxx); + } + } + } + + if (!on.isEmpty() || !off.isEmpty()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + int id = boneData.getId(); + if (!on.isEmpty()) { + NetworkUtils.send(on, this.audienceGlowData(id, true, color)); + } + + if (!off.isEmpty()) { + NetworkUtils.send(off, this.audienceGlowData(id, false, color)); + } + } + } + } + } + } + } + + private ClientboundSetEntityDataPacket audienceGlowData(int entityId, boolean glowing, int color) { + ArrayList> entityData = new ArrayList<>(2); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(glowing ? 96 : 32))); + if (glowing) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + + return new ClientboundSetEntityDataPacket(entityId, entityData); + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + set.add((Packet)this.pivotCameraResize(pivot)); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(destroy)))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(hitboxDestroy)))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)(u -> this.displayData(u, null, boneData, false, transformOnly))); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + AnimationLODHandler.LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(FriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CODEC == null) { + Field field = ClientboundCustomPayloadPacket.class.getField("GAMEPLAY_STREAM_CODEC"); + field.setAccessible(true); + CUSTOM_PAYLOAD_CODEC = (StreamCodec)field.get(null); + } + + return (Packet)CUSTOM_PAYLOAD_CODEC.decode(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData( + BulkEntityDataEncoder encoder, + UUID uuid, + @Nullable AnimationLODHandler.LODTracker tracker, + DisplayBone.BoneData boneData, + boolean force, + boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? new ClientboundSetEntityDataPacket(pivot.getId(), this.cameraPivotData(pivot.getCameraHeight().get())) + : new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private List> cameraPivotData(float height) { + return List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(8, EntityDataSerializers.FLOAT, 0.0F), + new DataValue(9, EntityDataSerializers.FLOAT, height) + ); + } + + private ClientboundSetPassengersPacket pivotMount(DisplayRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(DisplayRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundSetEntityDataPacket pivotCameraResize(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() && pivot.getCameraHeight().isDirty() + ? new ClientboundSetEntityDataPacket(pivot.getId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, pivot.getCameraHeight().get()))) + : null; + } + + private ClientboundAddEntityPacket displaySpawn(DisplayRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData( + UUID uuid, @Nullable AnimationLODHandler.LODTracker tracker, DisplayBone.BoneData boneData, boolean force, boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + ArrayList> entityData = new ArrayList<>(13); + if (!force && update != 0) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : lodTick)), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + entityData.add(new DataValue(16, EntityDataSerializers.INT, val)); + } + }, force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + } + }, force); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + + private ClientboundSetEntityDataPacket displayVisibleData(DisplayBone.BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)))); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color))); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val))); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F))); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)))); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()))); + this.cleanupQueue.add(bone::clearDirty); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(DisplayRenderer.Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(DisplayRenderer.Hitbox hitbox) { + return !hitbox.isPivotVisible() ? null : new ClientboundSetEntityDataPacket(hitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket hitboxSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(4); + hitbox.getWidth().ifDirty(val -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, val)), spawn); + hitbox.getHeight().ifDirty(val -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getHitboxId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(2); + hitbox.getShadowRadius().ifDirty(val -> entityData.add(new DataValue(18, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getShadowId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(DisplayRenderer.Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(DisplayRenderer.Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + return new ClientboundSetPassengersPacket(EntityContainer.of(hitbox.getPivotId(), passengers)); + } + } +} diff --git a/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/vfx/VFXDisplayParser.java b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..7f3a6be --- /dev/null +++ b/nms/v1_21_R1/src/main/java/com/ticxo/modelengine/v1_21_R1/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,124 @@ +package com.ticxo.modelengine.v1_21_R1.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R1.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R1.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R1.network.utils.Packets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(new int[]{vfx.getPivotId(), vfx.getModelId()})); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXDisplayRenderer.VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetEntityDataPacket(vfx.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXDisplayRenderer.VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXDisplayRenderer.VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(9); + if (spawn) { + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)32)); + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, 4096.0F)); + entityData.add(new DataValue(24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal())); + } else if (vfx.isModelDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + vfx.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + vfx.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + vfx.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + vfx.clearModelDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(vfx.getModelId(), entityData); + } + } + + private Object teleport(VFXDisplayRenderer.VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetPassengersPacket(EntityContainer.of(vfx.getPivotId(), vfx.getModelId())); + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSFields.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSFields.java new file mode 100644 index 0000000..18db7b3 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSFields.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_21_R2; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionUtils.ReflectionEnum { + ENTITY_dimensions(Entity.class, "bb", "dimensions"), + ENTITY_eyeHeight(Entity.class, "bc", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "cf", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "bn", "jumping"), + MOB_lookControl(Mob.class, "bP", "lookControl"), + MOB_moveControl(Mob.class, "bQ", "moveControl"), + MOB_navigation(Mob.class, "bS", "navigation"), + MOB_goalSelector(Mob.class, "bT", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "cb", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "I", "clientIsFloating"), + SERVER_COMMON_PACKET_LISTENER_IMPL_connection(ServerCommonPacketListenerImpl.class, "e", "connection"), + MOVE_CONTROL_operation(MoveControl.class, "k", "operation"), + TRACKED_ENTITY_serverEntity(TrackedEntity.class, "b", "serverEntity"), + TRACKED_ENTITY_range(TrackedEntity.class, "d", "range"), + LEVEL_threadSafeRandom(Level.class, "f", "threadSafeRandom"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "a", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "b", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(final Class target, final String obfuscated, final String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSHandler_v1_21_R2.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSHandler_v1_21_R2.java new file mode 100644 index 0000000..71ef6fd --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSHandler_v1_21_R2.java @@ -0,0 +1,179 @@ +package com.ticxo.modelengine.v1_21_R2; + +import com.mojang.math.MatrixUtil; +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.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R2.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_21_R2.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R2.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_21_R2.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_21_R2.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_21_R2.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_21_R2.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_21_R2.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_21_R2.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.entity.Entity; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_21_R2 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + FriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, NetworkUtils.create(ClientboundSetPassengersPacket.class, byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(EntityContainer.of(mountId, passengerIds)); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSMethods.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSMethods.java new file mode 100644 index 0000000..7da4f67 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/NMSMethods.java @@ -0,0 +1,48 @@ +package com.ticxo.modelengine.v1_21_R2; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements ReflectionUtils.MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "i", "getInstrument", ItemStack.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityContainer.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityContainer.java new file mode 100644 index 0000000..b0daa8a --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityContainer.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_21_R2.entity; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.syncher.SynchedEntityData.Builder; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.ApiStatus.Internal; + +@Internal +public class EntityContainer extends Entity { + public static EntityContainer of(int id) { + return new EntityContainer(id); + } + + public static Entity of(int id, int... passengerIds) { + EntityContainer container = of(id); + container.setPassengers(Arrays.stream(passengerIds).mapToObj(EntityContainer::new).toList()); + return container; + } + + public static Entity of(int id, Collection passengerIds) { + EntityContainer container = of(id); + container.setPassengers(passengerIds.stream().map(EntityContainer::new).toList()); + return container; + } + + private EntityContainer(int id) { + super(EntityType.INTERACTION, MinecraftServer.getServer().overworld()); + this.setId(id); + this.setPosRaw(0.0, 0.0, 0.0); + this.setRot(0.0F, 0.0F); + this.setOnGround(false); + } + + protected void setPassengers(List passengers) { + this.passengers = ImmutableList.copyOf(passengers); + } + + protected void defineSynchedData(@NotNull Builder builder) { + } + + public boolean hurtServer(ServerLevel world, DamageSource source, float amount) { + return false; + } + + protected void readAdditionalSaveData(@NotNull CompoundTag nbt) { + } + + protected void addAdditionalSaveData(@NotNull CompoundTag nbt) { + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityHandlerImpl.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..0985a11 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityHandlerImpl.java @@ -0,0 +1,742 @@ +package com.ticxo.modelengine.v1_21_R2.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_21_R2.NMSFields; +import com.ticxo.modelengine.v1_21_R2.NMSMethods; +import com.ticxo.modelengine.v1_21_R2.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_21_R2.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_21_R2.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_21_R2.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_21_R2.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_21_R2.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_21_R2.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R2.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_21_R2.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R2.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.minecraft.core.Holder; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult.Fail; +import net.minecraft.world.InteractionResult.Pass; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.TryEmptyHandInteraction; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityAttachments; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemUseAnimation; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + float width = (float)hitbox.getMaxWidth(); + float height = (float)hitbox.getHeight(); + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions(width, height, (float)hitbox.getEyeHeight(), EntityAttachments.createDefault(width, height), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + if (EntityUtils.nms(entity) instanceof LivingEntity living) { + living.getAttributes().registerAttribute(Attributes.STEP_HEIGHT); + Objects.requireNonNull(living.getAttribute(Attributes.STEP_HEIGHT)).setBaseValue(height); + } + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityType.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y - nmsEntity.getVehicleAttachmentPoint(this.dummyArmorStand).y; + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + entity.getEntityId(), List.of(new DataValue(0, EntityDataSerializers.BYTE, data)) + ); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + switch (oldNav) { + case WallClimberNavigation wallClimberNavigation: + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + break; + case GroundPathNavigation groundPathNavigation: + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + break; + case FlyingPathNavigation flyingPathNavigation: + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + break; + case WaterBoundPathNavigation waterBoundPathNavigation: + newNav = new WaterBoundNavigationWrapper(mob); + break; + case AmphibiousPathNavigation amphibiousPathNavigation: + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + break; + default: + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var13) { + var13.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + ServerLevel level = ((CraftWorld)location.getWorld()).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity.level() instanceof ServerLevel worldserver) { + return nmsEntity.hurtServer(worldserver, damageSource, amount); + } + } + + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + + @Override + public EntityHandler.InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case Success success -> success.equals(net.minecraft.world.InteractionResult.SUCCESS_SERVER) + ? EntityHandler.InteractionResult.SUCCESS + : ( + success.equals(net.minecraft.world.InteractionResult.SUCCESS) + ? EntityHandler.InteractionResult.CONSUME_PARTIAL + : EntityHandler.InteractionResult.CONSUME + ); + case TryEmptyHandInteraction ignored -> EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED; + case Pass ignoredx -> EntityHandler.InteractionResult.PASS; + case Fail ignoredxx -> EntityHandler.InteractionResult.FAIL; + default -> throw new MatchException(null, null); + }; + } else { + return EntityHandler.InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket( + DynamicHitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA + ); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(DynamicHitbox.getHitboxId(), EntityUtils.DEFAULT_SLIME_DATA); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket( + EntityContainer.of(DynamicHitbox.getPivotId(), DynamicHitbox.getHitboxId()) + ); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0, 0.0F, 0.0F + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != ItemUseAnimation.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + player.getEntityId(), List.of(new DataValue(8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3))) + ); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call( + instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack, nmsPlayer.registryAccess() + ); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public Float getCameraEyeHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return nmsEntity.getDimensions(Pose.STANDING).eyeHeight(); + } + + @Override + public Float getCameraPivotHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + EntityDimensions dimensions = nmsEntity.getDimensions(nmsEntity.getPose()); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 attachment = ReflectionUtils.call(nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, dimensions, 1.0F); + return attachment == null ? null : (float)(dimensions.eyeHeight() - attachment.y); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = level.getChunkSource().chunkMap.entityMap; + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = lvl.getChunkSource().chunkMap.entityMap; + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3D(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + EntityHandler.BoxRelToCam relX = EntityHandler.BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + EntityHandler.BoxRelToCam relY = EntityHandler.BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + EntityHandler.BoxRelToCam relZ = EntityHandler.BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == EntityHandler.BoxRelToCam.INSIDE && relY == EntityHandler.BoxRelToCam.INSIDE && relZ == EntityHandler.BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.DUST, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityMetadataID.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityMetadataID.java new file mode 100644 index 0000000..c081e17 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityMetadataID.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.v1_21_R2.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityUtils.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityUtils.java new file mode 100644 index 0000000..d38f1f0 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/EntityUtils.java @@ -0,0 +1,30 @@ +package com.ticxo.modelengine.v1_21_R2.entity; + +import java.util.List; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.entity.CraftEntity; + +public class EntityUtils { + public static final List> DEFAULT_AREA_EFFECT_CLOUD_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(8, EntityDataSerializers.FLOAT, 0.0F) + ); + public static final List> DEFAULT_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(16, EntityDataSerializers.INT, 2) + ); + public static final List> DEFAULT_BAT_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE) + ); + public static final List> DEFAULT_ARMOR_STAND_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(15, EntityDataSerializers.BYTE, (byte)16) + ); + + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/OcclusionClipContext.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/OcclusionClipContext.java new file mode 100644 index 0000000..5b85935 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v1_21_R2.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape() == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (tX > 1.0 && tY > 1.0 && tZ > 1.0) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/TrackedEntityImpl.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..3ee32f2 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/TrackedEntityImpl.java @@ -0,0 +1,286 @@ +package com.ticxo.modelengine.v1_21_R2.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R2.NMSFields; +import com.ticxo.modelengine.v1_21_R2.NMSMethods; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } + + @Override + public boolean isViewerSetUnchanged() { + if ((!this.mayHaveForced || this.forcedPairing.isEmpty() && this.forcedRemove.isEmpty()) && this.playerPredicate == DEFAULT_PREDICATE) { + if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } else { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/BodyRotationControlWrapper.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..c23f1ae --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_21_R2.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/LookControlWrapper.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..31e22e0 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/LookControlWrapper.java @@ -0,0 +1,143 @@ +package com.ticxo.modelengine.v1_21_R2.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; +import org.spigotmc.ActivationRange; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/MoveControlWrapper.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..2c53f3a --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/controller/MoveControlWrapper.java @@ -0,0 +1,263 @@ +package com.ticxo.modelengine.v1_21_R2.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R2.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.Input; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + if (entity instanceof Player player) { + Input playerInput = player.getCurrentInput(); + controller.setInput( + new MountController.MountInput( + playerInput.isForward(), + playerInput.isBackward(), + playerInput.isLeft(), + playerInput.isRight(), + playerInput.isJump(), + playerInput.isSneak(), + playerInput.isSprint() + ) + ); + } else { + controller.setInput(new MountController.MountInput()); + } + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/hitbox/HitboxEntityImpl.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..f30f453 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,308 @@ +package com.ticxo.modelengine.v1_21_R2.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_21_R2.NMSFields; +import com.ticxo.modelengine.v1_21_R2.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + public boolean canBeHitByProjectile() { + return this.subHitbox.isCanBeHitByProjectile(); + } + + @NotNull + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + @NotNull + public Iterable getArmorSlots() { + return this.armorItems; + } + + @NotNull + public ItemStack getItemBySlot(EquipmentSlot slot) { + return switch (slot.getType()) { + case HAND -> (ItemStack)this.handItems.get(slot.getIndex()); + case HUMANOID_ARMOR -> (ItemStack)this.armorItems.get(slot.getIndex()); + case ANIMAL_ARMOR -> ItemStack.EMPTY; + default -> throw new MatchException(null, null); + }; + } + + public void setItemSlot(EquipmentSlot slot, @NotNull ItemStack stack) { + this.verifyEquippedItem(stack); + switch (slot.getType()) { + case HAND: + this.onEquipItem(slot, (ItemStack)this.handItems.set(slot.getIndex(), stack), stack); + break; + case HUMANOID_ARMOR: + this.onEquipItem(slot, (ItemStack)this.armorItems.set(slot.getIndex(), stack), stack); + } + } + + public boolean isInvisible() { + return true; + } + + public void push(@NotNull Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox() { + if (this.subHitbox == null) { + return super.makeBoundingBox(); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(@NotNull Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurtServer(@NotNull ServerLevel world, @NotNull DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurtServer(world, source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + BaseEntity baseEntity = this.bone.getActiveModel().getModeledEntity().getBase(); + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return baseEntity.hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, @NotNull InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, + entity, + new Vector(0, 0, 0), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact( + this, + player.getBukkitEntity(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND + ); + + return (InteractionResult)(switch (result) { + case SUCCESS -> InteractionResult.SUCCESS_SERVER; + case SUCCESS_NO_ITEM_USED -> InteractionResult.TRY_WITH_EMPTY_HAND; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.SUCCESS; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }); + } + } + + public boolean shouldBeSaved() { + return false; + } + + @NotNull + public CraftEntity getBukkitEntity() { + CraftEntity bukkitEntity = this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + CraftEntity var5 = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(var5); + return var5; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(@NotNull RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/hitbox/OBB.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/hitbox/OBB.java new file mode 100644 index 0000000..d225e74 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R2.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..c9c8cd8 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..4cea141 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/GroundNavigationWrapper.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..575ab45 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..0c3a9b7 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + this.setCanOpenDoors(oldNav.canOpenDoors()); + this.setCanPassDoors(oldNav.canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..e6fc1ce --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_21_R2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/ModelEngineChannelHandler.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..930de8b --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/ModelEngineChannelHandler.java @@ -0,0 +1,457 @@ +package com.ticxo.modelengine.v1_21_R2.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R2.NMSFields; +import com.ticxo.modelengine.v1_21_R2.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R2.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntList; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundEntityPositionSyncPacket.class, this::handlePositionSync) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove) + .register(ServerboundClientTickEndPacket.class, this::handleClientTickEnd); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet rawPacket && asClientPacket(rawPacket) instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + Collection> post = this.writeInterceptors.acceptPost(result); + if (!post.isEmpty()) { + list.addAll(post); + } + } + } + + if (!list.isEmpty()) { + Packet var12 = new ClientboundBundlePacket(list); + super.write(ctx, var12, promise); + } + } else { + Packet var13 = this.writeInterceptors.accept(packet); + if (var13 == null) { + return; + } + + Collection> post = this.writeInterceptors.acceptPost(var13); + if (post.isEmpty()) { + super.write(ctx, var13, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var13); + list.addAll(post); + Packet var14 = new ClientboundBundlePacket(list); + super.write(ctx, var14, promise); + } + } + } catch (Throwable var11) { + var11.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List> handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List> handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + List> list = null; + Optional maybeMount = model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT); + if (maybeMount.isPresent() && maybeMount.get() instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + MountRenderer.Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + if (mount == null) { + return null; + } + + CollectionDataTracker ids = mount.getPassengers(); + list = new ArrayList<>(); + list.add(new ClientboundSetPassengersPacket(EntityContainer.of(mount.getMountId(), ids))); + } + } + + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + IntList ids = packet.getEntityIds(); + + for (int i = 0; i < ids.size(); i++) { + this.markViewersDirty(ids.getInt(i)); + } + + int[] set = packet.getEntityIds().intStream().filter(id -> ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE).toArray(); + return set.length == packet.getEntityIds().size() ? packet : new ClientboundRemoveEntitiesPacket(IntArrayList.wrap(set)); + } + + private > T handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readClientbound(packet); + + Packet var4; + try { + int id = buf.readVarInt(); + var4 = ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } finally { + buf.release(); + } + + return (T)var4; + } + + private > T handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundEntityPositionSyncPacket handlePositionSync(ClientboundEntityPositionSyncPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + int id = packet.entityId(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + return !changed ? packet : new ClientboundSetPassengersPacket(EntityContainer.of(packet.getVehicle(), new IntArrayList(merged))); + } + } + } + + private Packet handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readServerbound(packet); + + int entityId; + int action; + try { + entityId = buf.readVarInt(); + action = buf.readVarInt(); + } finally { + buf.release(); + } + + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), action, packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, action, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, action, packet) : packet); + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountController.MountInput input = controller.getInput(); + if (input == null) { + controller.setInput( + new MountController.MountInput( + inputPacket.input().forward(), + inputPacket.input().backward(), + inputPacket.input().left(), + inputPacket.input().right(), + inputPacket.input().jump(), + inputPacket.input().shift(), + inputPacket.input().sprint() + ) + ); + } else { + input.setForward(inputPacket.input().forward()); + input.setBackward(inputPacket.input().backward()); + input.setLeft(inputPacket.input().left()); + input.setRight(inputPacket.input().right()); + input.setJump(inputPacket.input().jump()); + input.setSneak(inputPacket.input().shift()); + input.setSprint(inputPacket.input().sprint()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + if (!ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + private ServerboundClientTickEndPacket handleClientTickEnd(ServerboundClientTickEndPacket packet) { + if (ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + @SuppressWarnings("unchecked") + private static Packet asClientPacket(Object packet) { + return (Packet)packet; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/NetworkHandlerImpl.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..061200d --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/NetworkHandlerImpl.java @@ -0,0 +1,141 @@ +package com.ticxo.modelengine.v1_21_R2.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R2.NMSFields; +import com.ticxo.modelengine.v1_21_R2.network.utils.Bundler; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection> collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/patch/PatchedServerGamePacketListener.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..f0859fb --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,439 @@ +package com.ticxo.modelengine.v1_21_R2.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R2.NMSMethods; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.SwingSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(final ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().serverLevel()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.serverLevel(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + ModelBone hitBone = null; + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel == null) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(interactPacket.getRelayedId()); + if (hitbox != null) { + hitBone = hitbox.getBone(); + activeModel = hitBone.getActiveModel(); + } + } + + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + final ActiveModel finalActiveModel = activeModel; + final ModelBone finalHitBone = hitBone; + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + null, + finalHitBone + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + position, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + position, + finalHitBone + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.ATTACK, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, null); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, pos); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent( + craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND, null + ); + } + } + ); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= player.entityInteractionRange() * player.entityInteractionRange())) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelected().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + if (player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + ServerEntity serverEntity = entity.moonrise$getTrackedEntity().serverEntity; + List> list = new ArrayList<>(); + serverEntity.sendPairingData(player, list::add); + player.connection.send(new ClientboundBundlePacket(list)); + } + + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem) { + List> data = entity.getEntityData().packAll(); + if (data != null && player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + player.connection.send(new ClientboundSetEntityDataPacket(entity.getId(), data)); + } + + if (entity instanceof Allay allay) { + List> equipment = Arrays.stream(EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.getItemBySlot(slot))) + .collect(Collectors.toList()); + connection.send(new ClientboundSetEquipmentPacket(entity.getId(), equipment)); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.serverLevel()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.serverLevel(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level().clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.isSameItemSameComponents(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand, + movingobjectpositionblock.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, itemstack, enumhand); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.resyncUsingItem(player); + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent( + CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacketWrapper packet, InteractionHand hand, @Nullable Vec3 vector + ) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.isAttack(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND, + vector != null ? new Vector(vector.x, vector.y, vector.z) : null + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..0aad093 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,75 @@ +package com.ticxo.modelengine.v1_21_R2.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper implements Packet { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + private final boolean isAttack; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, int action, ServerboundInteractPacket original) { + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + this.isAttack = action == 1; + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_INTERACT; + } + + public int getEntityId() { + return this.originalId; + } + + public boolean isAttack() { + return this.isAttack; + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/BulkEntityDataEncoder.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..8eeb68a --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R2.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/Bundler.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/Bundler.java new file mode 100644 index 0000000..6136de7 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_21_R2.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.getLast(); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection> packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.getLast(); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet packet : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/NetworkUtils.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/NetworkUtils.java new file mode 100644 index 0000000..c291bb3 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/NetworkUtils.java @@ -0,0 +1,343 @@ +package com.ticxo.modelengine.v1_21_R2.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R2.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R2.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static final ProtocolInfo CLIENTBOUND_CODEC = GameProtocols.CLIENTBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + public static final ProtocolInfo SERVERBOUND_CODEC = GameProtocols.SERVERBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + private static final Map, Constructor> PACKET_CONSTRUCTOR = new HashMap<>(); + + public static FriendlyByteBuf createByteBuf() { + return new FriendlyByteBuf(Unpooled.buffer()); + } + + public static FriendlyByteBuf createByteBuf(Consumer consumer) { + FriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static > T create(Class clazz, FriendlyByteBuf buf) { + Constructor constructor = PACKET_CONSTRUCTOR.computeIfAbsent(clazz, aClass -> { + try { + Constructor c = aClass.getDeclaredConstructor(RegistryFriendlyByteBuf.class); + c.setAccessible(true); + return c; + } catch (NoSuchMethodException var4x) { + try { + Constructor cx = aClass.getDeclaredConstructor(FriendlyByteBuf.class); + cx.setAccessible(true); + return cx; + } catch (NoSuchMethodException var3) { + throw new RuntimeException(var3); + } + } + }); + + try { + return (T)constructor.newInstance(buf); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException var4) { + throw new RuntimeException(var4); + } + } + + public static FriendlyByteBuf readServerbound(Packet packet) { + FriendlyByteBuf buf = createByteBuf(); + SERVERBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static FriendlyByteBuf readClientbound(Packet packet) { + FriendlyByteBuf buf = createByteBuf(); + CLIENTBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createCameraPivotSpawn(int id, UUID uuid, Vector3f pos, float height) { + ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket( + id, uuid, pos.x, pos.y - height, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createCameraPivotTeleport(int id, Vector3f pos, float height) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - height, pos.z); + ClientboundEntityPositionSyncPacket packet = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - 0.375, pos.z); + ClientboundEntityPositionSyncPacket tpHigher = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + container = EntityContainer.of(id); + container.setId(id); + container.setPosRaw(pos.x, pos.y - 0.5, pos.z); + ClientboundEntityPositionSyncPacket tpLower = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Object createCameraPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos, float height) { + if (codec == null) { + return createCameraPivotTeleport(id, pos, height); + } else { + return switch (codec.update(pos.x, pos.y - height, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createCameraPivotTeleport(id, pos, height); + }; + } + } + + public static Packets.PacketSupplier lodWrapper( + ModeledEntity modeledEntity, BiFunction> packetFunction + ) { + return uuid -> { + AnimationLODHandler.LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/PacketInterceptor.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..baa1b87 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/PacketInterceptor.java @@ -0,0 +1,84 @@ +package com.ticxo.modelengine.v1_21_R2.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor

    { + private final Map>, PacketInterceptor

    .Modifier>> registry = Maps.newConcurrentMap(); + private final Map>, PacketInterceptor

    .Listener>> postRegistry = Maps.newConcurrentMap(); + + public > PacketInterceptor

    register(Class clazz, Function> function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public > PacketInterceptor

    registerPost(Class clazz, Function>> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor

    .Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection> acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor

    .Listener listener = this.postRegistry.get(original.getClass()); + return (Collection>)(listener != null ? listener.listen(original) : List.of()); + } + } + + class Listener> { + private final Class clazz; + private final Function>> function; + + public Collection> listen(Packet original) { + try { + Collection> collection = this.function.apply(this.clazz.cast(original)); + return (Collection>)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(final Class clazz, final Function>> function) { + this.clazz = clazz; + this.function = function; + } + } + + class Modifier> { + private final Class clazz; + private final Function> function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(final Class clazz, final Function> function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/Packets.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/Packets.java new file mode 100644 index 0000000..12c3f4d --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_21_R2.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/HeldItemParser.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..60403b3 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/HeldItemParser.java @@ -0,0 +1,181 @@ +package com.ticxo.modelengine.v1_21_R2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R2.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapToInt(HeldItemRenderer.Item::getId)) + )) + ); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Map items = renderer.getRendered(); + IntArrayList entityIds = IntArrayList.toList(items.values().stream().mapToInt(HeldItemRenderer.Item::getId)); + entityIds.add(renderer.getId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + return new ClientboundSetEntityDataPacket(renderer.getId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, HeldItemRenderer.Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(HeldItemRenderer.Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(11); + if (spawn) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, this.viewRange)); + } else if (renderer.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + renderer.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), spawn); + renderer.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), spawn); + renderer.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + renderer.getModel() + .ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + renderer.getDisplay() + .ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getId(), entityData); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location loc = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(loc.getX(), loc.getY(), loc.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + EntityContainer container = EntityContainer.of(renderer.getId()); + container.setPosRaw(loc.getX(), loc.getY(), loc.getZ()); + return new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getId(), renderer.getPassengers())); + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/LeashParser.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/LeashParser.java new file mode 100644 index 0000000..34768e0 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/LeashParser.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.v1_21_R2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Map leashes = renderer.getRendered(); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(IntArrayList.toList(leashes.values().stream().mapMultiToInt((leash, intConsumer) -> { + intConsumer.accept(leash.getLeashId()); + intConsumer.accept(leash.getPivotId()); + })))); + } + } + + private Packets.PacketSupplier pivotSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + + private ClientboundAddEntityPacket leashSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y - 0.45, pos.z - 0.2, 0.0F, 0.0F, EntityType.BAT, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetEntityDataPacket leashData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getLeashId(), EntityUtils.DEFAULT_BAT_DATA); + } + + private ClientboundSetPassengersPacket mount(LeashRenderer.Leash renderer) { + ArrayList passengers = new ArrayList<>(1); + passengers.add(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), passengers)); + } + + private Object move(LeashRenderer.Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + } + + private ClientboundSetEntityLinkPacket link(LeashRenderer.Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(EntityContainer.of(renderer.getLeashId()), EntityContainer.of(renderer.getConnected().get())); + } + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/MountParser.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/MountParser.java new file mode 100644 index 0000000..b9d7a72 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/MountParser.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.v1_21_R2.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R2.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getMountId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Collection mounts = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(mounts.size() * 2); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getMountId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(MountRenderer.Mount renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket mountSpawn(MountRenderer.Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getMountId())); + } + + private ClientboundSetPassengersPacket mount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getMountId(), renderer.getPassengers())); + } + + private Packets.PacketSupplier pivotMove(MountRenderer.Mount renderer) { + return NetworkUtils.createPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(MountRenderer.Mount renderer) { + return new Rot(renderer.getMountId(), renderer.getYaw().get(), (byte)0, false); + } + + private ClientboundSetEntityDataPacket mountHealth(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, renderer.getHealth().get()))); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(MountRenderer.Mount renderer) { + AttributeInstance attributeInstance = new AttributeInstance(Attributes.MAX_HEALTH, onDirty -> {}); + attributeInstance.setBaseValue(renderer.getMaxHealth().get().floatValue()); + return new ClientboundUpdateAttributesPacket(renderer.getMountId(), Lists.newArrayList(new AttributeInstance[]{attributeInstance})); + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/NameTagParser.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..b67d8b7 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/NameTagParser.java @@ -0,0 +1,184 @@ +package com.ticxo.modelengine.v1_21_R2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Component.Serializer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTagRenderer.NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTagRenderer.NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Collection nameTags = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(nameTags.size() * 2); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + return !spawn ? null : new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTagRenderer.NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(7); + renderer.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + renderer.getTranslate().ifDirty(flag -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getScale().ifDirty(flag -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getTextOpacity().ifDirty(flag -> entityData.add(new DataValue(26, EntityDataSerializers.BYTE, flag)), spawn); + renderer.getBackgroundColor().ifDirty(flag -> entityData.add(new DataValue(25, EntityDataSerializers.INT, flag)), spawn); + renderer.getStyle().ifDirty(flags -> entityData.add(new DataValue(27, EntityDataSerializers.BYTE, flags)), spawn); + renderer.getLineWidth().ifDirty(flag -> entityData.add(new DataValue(24, EntityDataSerializers.INT, flag)), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new MatchException(null, null); + }; + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, value)); + }, spawn); + renderer.getJsonString() + .ifDirty( + jsonString -> { + if (jsonString == null) { + entityData.add(new DataValue(23, EntityDataSerializers.COMPONENT, Component.empty())); + } else { + entityData.add( + new DataValue(23, EntityDataSerializers.COMPONENT, Serializer.fromJson(jsonString, MinecraftServer.getServer().registryAccess())) + ); + } + }, + spawn + ); + renderer.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getTagId(), entityData); + } + } + + private Object pivotMove(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTagRenderer.NameTag renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getTagId())); + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/SegmentParser.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..36d3211 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/SegmentParser.java @@ -0,0 +1,205 @@ +package com.ticxo.modelengine.v1_21_R2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R2.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (SegmentRenderer.Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + IntArrayList destroy = new IntArrayList(); + + for (SegmentRenderer.Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(destroy))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(SegmentRenderer.Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SegmentRenderer.Pivot pivot) { + return new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(SegmentRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(SegmentRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(SegmentRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + ArrayList> entityData = new ArrayList<>(13); + if (force) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } else if (bone.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : 1)), force); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), force); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/SubHitboxParser.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..a94228d --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/behavior/SubHitboxParser.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R2.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitboxRenderer.SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Collection subHitboxes = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(subHitboxes.size() * 2); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private Object pivotMove(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getHitboxId())); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitboxRenderer.SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitboxRenderer.SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(4); + renderer.getWidth().ifDirty(width -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, width)), spawn); + renderer.getHeight().ifDirty(height -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, height)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getHitboxId(), entityData); + } + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/model/DisplayParser.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/model/DisplayParser.java new file mode 100644 index 0000000..2fa9eaf --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/model/DisplayParser.java @@ -0,0 +1,789 @@ +package com.ticxo.modelengine.v1_21_R2.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R2.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static StreamCodec CUSTOM_PAYLOAD_CODEC; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + if (renderer.hasGlowAudience()) { + this.updateAudienceGlow(renderer, data.getTracking().keySet(), data.getStartTracking(), this.noCullForcePlayers); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + private void updateAudienceGlow(DisplayRenderer renderer, Set current, Set startTracking, Set forceUpdates) { + for (DisplayBone bone : renderer.getRendered().values()) { + Set audience = bone.getGlowAudience().get(); + if (audience != null) { + boolean changed = bone.isAudienceGlowDirty(); + if (changed || !startTracking.isEmpty() || !forceUpdates.isEmpty()) { + boolean glowing = bone.getAudienceGlowing().get(); + int color = bone.getAudienceGlowColor().get(); + Set on = new HashSet<>(); + Set off = new HashSet<>(); + if (changed) { + for (UUID uuid : current) { + if (glowing && audience.contains(uuid)) { + on.add(uuid); + } else { + off.add(uuid); + } + } + + bone.clearAudienceGlowDirty(); + } else if (glowing) { + for (UUID uuidx : startTracking) { + if (audience.contains(uuidx)) { + on.add(uuidx); + } + } + + for (UUID uuidxx : forceUpdates) { + if (audience.contains(uuidxx)) { + on.add(uuidxx); + } + } + } + + if (!on.isEmpty() || !off.isEmpty()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + int id = boneData.getId(); + if (!on.isEmpty()) { + NetworkUtils.send(on, this.audienceGlowData(id, true, color)); + } + + if (!off.isEmpty()) { + NetworkUtils.send(off, this.audienceGlowData(id, false, color)); + } + } + } + } + } + } + } + + private ClientboundSetEntityDataPacket audienceGlowData(int entityId, boolean glowing, int color) { + ArrayList> entityData = new ArrayList<>(2); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(glowing ? 96 : 32))); + if (glowing) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + + return new ClientboundSetEntityDataPacket(entityId, entityData); + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + set.add((Packet)this.pivotCameraResize(pivot)); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(destroy)))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(hitboxDestroy)))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)(u -> this.displayData(u, null, boneData, false, transformOnly))); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + AnimationLODHandler.LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + FriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(FriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CODEC == null) { + Field field = ClientboundCustomPayloadPacket.class.getField("GAMEPLAY_STREAM_CODEC"); + field.setAccessible(true); + CUSTOM_PAYLOAD_CODEC = (StreamCodec)field.get(null); + } + + return (Packet)CUSTOM_PAYLOAD_CODEC.decode(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData( + BulkEntityDataEncoder encoder, + UUID uuid, + @Nullable AnimationLODHandler.LODTracker tracker, + DisplayBone.BoneData boneData, + boolean force, + boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? new ClientboundSetEntityDataPacket(pivot.getId(), this.cameraPivotData(pivot.getCameraHeight().get())) + : new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private List> cameraPivotData(float height) { + return List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(8, EntityDataSerializers.FLOAT, 0.0F), + new DataValue(9, EntityDataSerializers.FLOAT, height) + ); + } + + private ClientboundSetPassengersPacket pivotMount(DisplayRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(DisplayRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundSetEntityDataPacket pivotCameraResize(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() && pivot.getCameraHeight().isDirty() + ? new ClientboundSetEntityDataPacket(pivot.getId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, pivot.getCameraHeight().get()))) + : null; + } + + private ClientboundAddEntityPacket displaySpawn(DisplayRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData( + UUID uuid, @Nullable AnimationLODHandler.LODTracker tracker, DisplayBone.BoneData boneData, boolean force, boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + ArrayList> entityData = new ArrayList<>(13); + if (!force && update != 0) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : lodTick)), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + entityData.add(new DataValue(16, EntityDataSerializers.INT, val)); + } + }, force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + } + }, force); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + + private ClientboundSetEntityDataPacket displayVisibleData(DisplayBone.BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)))); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color))); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val))); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F))); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)))); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()))); + this.cleanupQueue.add(bone::clearDirty); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(DisplayRenderer.Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(DisplayRenderer.Hitbox hitbox) { + return !hitbox.isPivotVisible() ? null : new ClientboundSetEntityDataPacket(hitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket hitboxSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(4); + hitbox.getWidth().ifDirty(val -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, val)), spawn); + hitbox.getHeight().ifDirty(val -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getHitboxId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(2); + hitbox.getShadowRadius().ifDirty(val -> entityData.add(new DataValue(18, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getShadowId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(DisplayRenderer.Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(DisplayRenderer.Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + return new ClientboundSetPassengersPacket(EntityContainer.of(hitbox.getPivotId(), passengers)); + } + } +} diff --git a/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/vfx/VFXDisplayParser.java b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..14bd167 --- /dev/null +++ b/nms/v1_21_R2/src/main/java/com/ticxo/modelengine/v1_21_R2/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,124 @@ +package com.ticxo.modelengine.v1_21_R2.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R2.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R2.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R2.network.utils.Packets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(new int[]{vfx.getPivotId(), vfx.getModelId()})); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXDisplayRenderer.VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetEntityDataPacket(vfx.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXDisplayRenderer.VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXDisplayRenderer.VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(9); + if (spawn) { + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)32)); + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, 4096.0F)); + entityData.add(new DataValue(24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal())); + } else if (vfx.isModelDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + vfx.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + vfx.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + vfx.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + vfx.clearModelDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(vfx.getModelId(), entityData); + } + } + + private Object teleport(VFXDisplayRenderer.VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetPassengersPacket(EntityContainer.of(vfx.getPivotId(), vfx.getModelId())); + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSFields.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSFields.java new file mode 100644 index 0000000..2b4fda3 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSFields.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_21_R3; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionUtils.ReflectionEnum { + ENTITY_dimensions(Entity.class, "bb", "dimensions"), + ENTITY_eyeHeight(Entity.class, "bc", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "ce", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "bm", "jumping"), + MOB_lookControl(Mob.class, "bO", "lookControl"), + MOB_moveControl(Mob.class, "bP", "moveControl"), + MOB_navigation(Mob.class, "bR", "navigation"), + MOB_goalSelector(Mob.class, "bS", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "ca", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "I", "clientIsFloating"), + SERVER_COMMON_PACKET_LISTENER_IMPL_connection(ServerCommonPacketListenerImpl.class, "e", "connection"), + MOVE_CONTROL_operation(MoveControl.class, "k", "operation"), + TRACKED_ENTITY_serverEntity(TrackedEntity.class, "b", "serverEntity"), + TRACKED_ENTITY_range(TrackedEntity.class, "d", "range"), + LEVEL_threadSafeRandom(Level.class, "f", "threadSafeRandom"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "a", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "b", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(final Class target, final String obfuscated, final String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSHandler_v1_21_R3.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSHandler_v1_21_R3.java new file mode 100644 index 0000000..f9f138c --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSHandler_v1_21_R3.java @@ -0,0 +1,231 @@ +package com.ticxo.modelengine.v1_21_R3; + +import com.mojang.math.MatrixUtil; +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.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R3.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_21_R3.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R3.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_21_R3.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_21_R3.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_21_R3.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_21_R3.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_21_R3.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_21_R3.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.components.CustomModelDataComponent; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_21_R3 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + private boolean manualTranslucencyOrder; + private boolean forceCMD; + + public NMSHandler_v1_21_R3() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + public void updateConfig() { + this.manualTranslucencyOrder = ConfigProperty.MANUAL_TRANSLUCENCY_ORDER.getBoolean(); + this.forceCMD = ConfigProperty.FORCE_CMD.getBoolean(); + } + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + RegistryFriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, NetworkUtils.create(ClientboundSetPassengersPacket.class, byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public Set createStack(ItemModelData data, ItemModelData.Context context) { + if (this.forceCMD) { + return NMSHandler.super.createStack(data, context); + } else { + ItemStack item = new ItemStack(this.manualTranslucencyOrder && !data.isTranslucent() ? Material.GLASS : Material.BONE); + item.editMeta(itemMeta -> { + itemMeta.setItemModel(data.getSingleComposite().model()); + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(context.color())); + if (data.getVariant() != null) { + cmdComp.setStrings(List.of(data.getVariant())); + } + + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return Set.of(item); + } + } + + @Override + public boolean colorStack(ItemStack stack, Color color) { + stack.editMeta(itemMeta -> { + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(color)); + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return true; + } + + @Override + public void applyPlayerHeadItemModel(ItemStack stack) { + stack.editMeta(meta -> meta.setItemModel(this.getPlayerHeadModelKey())); + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(EntityContainer.of(mountId, passengerIds)); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSMethods.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSMethods.java new file mode 100644 index 0000000..1e33128 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/NMSMethods.java @@ -0,0 +1,49 @@ +package com.ticxo.modelengine.v1_21_R3; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.core.HolderLookup.Provider; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements ReflectionUtils.MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "i", "getInstrument", ItemStack.class, Provider.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityContainer.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityContainer.java new file mode 100644 index 0000000..17d854e --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityContainer.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_21_R3.entity; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.syncher.SynchedEntityData.Builder; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.ApiStatus.Internal; + +@Internal +public class EntityContainer extends Entity { + public static EntityContainer of(int id) { + return new EntityContainer(id); + } + + public static Entity of(int id, int... passengerIds) { + EntityContainer container = of(id); + container.setPassengers(Arrays.stream(passengerIds).mapToObj(EntityContainer::new).toList()); + return container; + } + + public static Entity of(int id, Collection passengerIds) { + EntityContainer container = of(id); + container.setPassengers(passengerIds.stream().map(EntityContainer::new).toList()); + return container; + } + + private EntityContainer(int id) { + super(EntityType.INTERACTION, MinecraftServer.getServer().overworld()); + this.setId(id); + this.setPosRaw(0.0, 0.0, 0.0); + this.setRot(0.0F, 0.0F); + this.setOnGround(false); + } + + protected void setPassengers(List passengers) { + this.passengers = ImmutableList.copyOf(passengers); + } + + protected void defineSynchedData(@NotNull Builder builder) { + } + + public boolean hurtServer(ServerLevel world, DamageSource source, float amount) { + return false; + } + + protected void readAdditionalSaveData(@NotNull CompoundTag nbt) { + } + + protected void addAdditionalSaveData(@NotNull CompoundTag nbt) { + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityHandlerImpl.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..7b098b6 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityHandlerImpl.java @@ -0,0 +1,742 @@ +package com.ticxo.modelengine.v1_21_R3.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_21_R3.NMSFields; +import com.ticxo.modelengine.v1_21_R3.NMSMethods; +import com.ticxo.modelengine.v1_21_R3.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_21_R3.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_21_R3.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_21_R3.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_21_R3.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_21_R3.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_21_R3.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R3.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_21_R3.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R3.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.minecraft.core.Holder; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult.Fail; +import net.minecraft.world.InteractionResult.Pass; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.TryEmptyHandInteraction; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityAttachments; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemUseAnimation; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + float width = (float)hitbox.getMaxWidth(); + float height = (float)hitbox.getHeight(); + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions(width, height, (float)hitbox.getEyeHeight(), EntityAttachments.createDefault(width, height), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + if (EntityUtils.nms(entity) instanceof LivingEntity living) { + living.getAttributes().registerAttribute(Attributes.STEP_HEIGHT); + Objects.requireNonNull(living.getAttribute(Attributes.STEP_HEIGHT)).setBaseValue(height); + } + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityType.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y - nmsEntity.getVehicleAttachmentPoint(this.dummyArmorStand).y; + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + entity.getEntityId(), List.of(new DataValue(0, EntityDataSerializers.BYTE, data)) + ); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + switch (oldNav) { + case WallClimberNavigation wallClimberNavigation: + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + break; + case GroundPathNavigation groundPathNavigation: + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + break; + case FlyingPathNavigation flyingPathNavigation: + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + break; + case WaterBoundPathNavigation waterBoundPathNavigation: + newNav = new WaterBoundNavigationWrapper(mob); + break; + case AmphibiousPathNavigation amphibiousPathNavigation: + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + break; + default: + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var13) { + var13.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + ServerLevel level = ((CraftWorld)location.getWorld()).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity.level() instanceof ServerLevel worldserver) { + return nmsEntity.hurtServer(worldserver, damageSource, amount); + } + } + + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + + @Override + public EntityHandler.InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case Success success -> success.equals(net.minecraft.world.InteractionResult.SUCCESS_SERVER) + ? EntityHandler.InteractionResult.SUCCESS + : ( + success.equals(net.minecraft.world.InteractionResult.SUCCESS) + ? EntityHandler.InteractionResult.CONSUME_PARTIAL + : EntityHandler.InteractionResult.CONSUME + ); + case TryEmptyHandInteraction ignored -> EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED; + case Pass ignoredx -> EntityHandler.InteractionResult.PASS; + case Fail ignoredxx -> EntityHandler.InteractionResult.FAIL; + default -> throw new MatchException(null, null); + }; + } else { + return EntityHandler.InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket( + DynamicHitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA + ); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(DynamicHitbox.getHitboxId(), EntityUtils.DEFAULT_SLIME_DATA); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket( + EntityContainer.of(DynamicHitbox.getPivotId(), DynamicHitbox.getHitboxId()) + ); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0, 0.0F, 0.0F + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != ItemUseAnimation.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + player.getEntityId(), List.of(new DataValue(8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3))) + ); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call( + instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack, nmsPlayer.registryAccess() + ); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public Float getCameraEyeHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return nmsEntity.getDimensions(Pose.STANDING).eyeHeight(); + } + + @Override + public Float getCameraPivotHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + EntityDimensions dimensions = nmsEntity.getDimensions(nmsEntity.getPose()); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 attachment = ReflectionUtils.call(nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, dimensions, 1.0F); + return attachment == null ? null : (float)(dimensions.eyeHeight() - attachment.y); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = level.getChunkSource().chunkMap.entityMap; + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = lvl.getChunkSource().chunkMap.entityMap; + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3D(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + EntityHandler.BoxRelToCam relX = EntityHandler.BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + EntityHandler.BoxRelToCam relY = EntityHandler.BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + EntityHandler.BoxRelToCam relZ = EntityHandler.BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == EntityHandler.BoxRelToCam.INSIDE && relY == EntityHandler.BoxRelToCam.INSIDE && relZ == EntityHandler.BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.DUST, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityMetadataID.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityMetadataID.java new file mode 100644 index 0000000..04b4bb2 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityMetadataID.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.v1_21_R3.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityUtils.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityUtils.java new file mode 100644 index 0000000..42f63cc --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/EntityUtils.java @@ -0,0 +1,30 @@ +package com.ticxo.modelengine.v1_21_R3.entity; + +import java.util.List; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.entity.CraftEntity; + +public class EntityUtils { + public static final List> DEFAULT_AREA_EFFECT_CLOUD_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(8, EntityDataSerializers.FLOAT, 0.0F) + ); + public static final List> DEFAULT_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(16, EntityDataSerializers.INT, 2) + ); + public static final List> DEFAULT_BAT_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE) + ); + public static final List> DEFAULT_ARMOR_STAND_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(15, EntityDataSerializers.BYTE, (byte)16) + ); + + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/OcclusionClipContext.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/OcclusionClipContext.java new file mode 100644 index 0000000..d1e3694 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v1_21_R3.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape() == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (!(tX <= 1.0) && !(tY <= 1.0) && !(tZ <= 1.0)) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/TrackedEntityImpl.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..e444c13 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/TrackedEntityImpl.java @@ -0,0 +1,286 @@ +package com.ticxo.modelengine.v1_21_R3.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R3.NMSFields; +import com.ticxo.modelengine.v1_21_R3.NMSMethods; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } + + @Override + public boolean isViewerSetUnchanged() { + if ((!this.mayHaveForced || this.forcedPairing.isEmpty() && this.forcedRemove.isEmpty()) && this.playerPredicate == DEFAULT_PREDICATE) { + if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } else { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/BodyRotationControlWrapper.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..911ddbd --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_21_R3.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/LookControlWrapper.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..cf29271 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/LookControlWrapper.java @@ -0,0 +1,152 @@ +package com.ticxo.modelengine.v1_21_R3.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import io.papermc.paper.entity.activation.ActivationRange; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + private MovementOverride movementOverride; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateDirection(this, this.modeledEntity); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/MoveControlWrapper.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..3749a38 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/controller/MoveControlWrapper.java @@ -0,0 +1,272 @@ +package com.ticxo.modelengine.v1_21_R3.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R3.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.Input; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + protected MovementOverride movementOverride; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateMovement(this, modeledEntity); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + if (entity instanceof Player player) { + Input playerInput = player.getCurrentInput(); + controller.setInput( + new MountController.MountInput( + playerInput.isForward(), + playerInput.isBackward(), + playerInput.isLeft(), + playerInput.isRight(), + playerInput.isJump(), + playerInput.isSneak(), + playerInput.isSprint() + ) + ); + } else { + controller.setInput(new MountController.MountInput()); + } + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/hitbox/HitboxEntityImpl.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..e1efc5f --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,308 @@ +package com.ticxo.modelengine.v1_21_R3.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_21_R3.NMSFields; +import com.ticxo.modelengine.v1_21_R3.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + public boolean canBeHitByProjectile() { + return this.subHitbox.isCanBeHitByProjectile(); + } + + @NotNull + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + @NotNull + public Iterable getArmorSlots() { + return this.armorItems; + } + + @NotNull + public ItemStack getItemBySlot(EquipmentSlot slot) { + return switch (slot.getType()) { + case HAND -> (ItemStack)this.handItems.get(slot.getIndex()); + case HUMANOID_ARMOR -> (ItemStack)this.armorItems.get(slot.getIndex()); + case ANIMAL_ARMOR -> ItemStack.EMPTY; + default -> throw new MatchException(null, null); + }; + } + + public void setItemSlot(EquipmentSlot slot, @NotNull ItemStack stack) { + this.verifyEquippedItem(stack); + switch (slot.getType()) { + case HAND: + this.onEquipItem(slot, (ItemStack)this.handItems.set(slot.getIndex(), stack), stack); + break; + case HUMANOID_ARMOR: + this.onEquipItem(slot, (ItemStack)this.armorItems.set(slot.getIndex(), stack), stack); + } + } + + public boolean isInvisible() { + return true; + } + + public void push(@NotNull Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox(Vec3 position) { + if (this.subHitbox == null) { + return super.makeBoundingBox(position); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(@NotNull Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurtServer(@NotNull ServerLevel world, @NotNull DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurtServer(world, source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + BaseEntity baseEntity = this.bone.getActiveModel().getModeledEntity().getBase(); + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return baseEntity.hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, @NotNull InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, + entity, + new Vector(0, 0, 0), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact( + this, + player.getBukkitEntity(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND + ); + + return (InteractionResult)(switch (result) { + case SUCCESS -> InteractionResult.SUCCESS_SERVER; + case SUCCESS_NO_ITEM_USED -> InteractionResult.TRY_WITH_EMPTY_HAND; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.SUCCESS; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }); + } + } + + public boolean shouldBeSaved() { + return false; + } + + @NotNull + public CraftEntity getBukkitEntity() { + CraftEntity bukkitEntity = this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + CraftEntity var5 = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(var5); + return var5; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(@NotNull RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/hitbox/OBB.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/hitbox/OBB.java new file mode 100644 index 0000000..3610382 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R3.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..706e577 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..da98e06 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/GroundNavigationWrapper.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..3e6a0f3 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..856b9d7 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..ff254bb --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_21_R3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/ModelEngineChannelHandler.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..3d761e1 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/ModelEngineChannelHandler.java @@ -0,0 +1,457 @@ +package com.ticxo.modelengine.v1_21_R3.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R3.NMSFields; +import com.ticxo.modelengine.v1_21_R3.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R3.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntList; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundEntityPositionSyncPacket.class, this::handlePositionSync) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove) + .register(ServerboundClientTickEndPacket.class, this::handleClientTickEnd); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet rawPacket && asClientPacket(rawPacket) instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + Collection> post = this.writeInterceptors.acceptPost(result); + if (!post.isEmpty()) { + list.addAll(post); + } + } + } + + if (!list.isEmpty()) { + Packet var12 = new ClientboundBundlePacket(list); + super.write(ctx, var12, promise); + } + } else { + Packet var13 = this.writeInterceptors.accept(packet); + if (var13 == null) { + return; + } + + Collection> post = this.writeInterceptors.acceptPost(var13); + if (post.isEmpty()) { + super.write(ctx, var13, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var13); + list.addAll(post); + Packet var14 = new ClientboundBundlePacket(list); + super.write(ctx, var14, promise); + } + } + } catch (Throwable var11) { + var11.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List> handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List> handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + List> list = null; + Optional maybeMount = model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT); + if (maybeMount.isPresent() && maybeMount.get() instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + MountRenderer.Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + if (mount == null) { + return null; + } + + CollectionDataTracker ids = mount.getPassengers(); + list = new ArrayList<>(); + list.add(new ClientboundSetPassengersPacket(EntityContainer.of(mount.getMountId(), ids))); + } + } + + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + IntList ids = packet.getEntityIds(); + + for (int i = 0; i < ids.size(); i++) { + this.markViewersDirty(ids.getInt(i)); + } + + int[] set = packet.getEntityIds().intStream().filter(id -> ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE).toArray(); + return set.length == packet.getEntityIds().size() ? packet : new ClientboundRemoveEntitiesPacket(IntArrayList.wrap(set)); + } + + private > T handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readClientbound(packet); + + Packet var4; + try { + int id = buf.readVarInt(); + var4 = ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } finally { + buf.release(); + } + + return (T)var4; + } + + private > T handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundEntityPositionSyncPacket handlePositionSync(ClientboundEntityPositionSyncPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + int id = packet.entityId(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + return !changed ? packet : new ClientboundSetPassengersPacket(EntityContainer.of(packet.getVehicle(), new IntArrayList(merged))); + } + } + } + + private Packet handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readServerbound(packet); + + int entityId; + int action; + try { + entityId = buf.readVarInt(); + action = buf.readVarInt(); + } finally { + buf.release(); + } + + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), action, packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, action, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, action, packet) : packet); + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountController.MountInput input = controller.getInput(); + if (input == null) { + controller.setInput( + new MountController.MountInput( + inputPacket.input().forward(), + inputPacket.input().backward(), + inputPacket.input().left(), + inputPacket.input().right(), + inputPacket.input().jump(), + inputPacket.input().shift(), + inputPacket.input().sprint() + ) + ); + } else { + input.setForward(inputPacket.input().forward()); + input.setBackward(inputPacket.input().backward()); + input.setLeft(inputPacket.input().left()); + input.setRight(inputPacket.input().right()); + input.setJump(inputPacket.input().jump()); + input.setSneak(inputPacket.input().shift()); + input.setSprint(inputPacket.input().sprint()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + if (!ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + private ServerboundClientTickEndPacket handleClientTickEnd(ServerboundClientTickEndPacket packet) { + if (ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + @SuppressWarnings("unchecked") + private static Packet asClientPacket(Object packet) { + return (Packet)packet; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/NetworkHandlerImpl.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..9678a07 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/NetworkHandlerImpl.java @@ -0,0 +1,141 @@ +package com.ticxo.modelengine.v1_21_R3.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R3.NMSFields; +import com.ticxo.modelengine.v1_21_R3.network.utils.Bundler; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection> collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/patch/PatchedServerGamePacketListener.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..275e5bb --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,439 @@ +package com.ticxo.modelengine.v1_21_R3.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R3.NMSMethods; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.SwingSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(final ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().serverLevel()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.serverLevel(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + ModelBone hitBone = null; + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel == null) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(interactPacket.getRelayedId()); + if (hitbox != null) { + hitBone = hitbox.getBone(); + activeModel = hitBone.getActiveModel(); + } + } + + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + final ActiveModel finalActiveModel = activeModel; + final ModelBone finalHitBone = hitBone; + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + null, + finalHitBone + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + position, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + position, + finalHitBone + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.ATTACK, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, null); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, pos); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent( + craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND, null + ); + } + } + ); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= player.entityInteractionRange() * player.entityInteractionRange())) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelected().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + if (player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + ServerEntity serverEntity = entity.moonrise$getTrackedEntity().serverEntity; + List> list = new ArrayList<>(); + serverEntity.sendPairingData(player, list::add); + player.connection.send(new ClientboundBundlePacket(list)); + } + + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelected().getItem() != origItem) { + List> data = entity.getEntityData().packAll(); + if (data != null && player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + player.connection.send(new ClientboundSetEntityDataPacket(entity.getId(), data)); + } + + if (entity instanceof Allay allay) { + List> equipment = Arrays.stream(EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.getItemBySlot(slot))) + .collect(Collectors.toList()); + connection.send(new ClientboundSetEquipmentPacket(entity.getId(), equipment)); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.serverLevel()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.serverLevel(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level().clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.isSameItemSameComponents(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand, + movingobjectpositionblock.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, itemstack, enumhand); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.resyncUsingItem(player); + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent( + CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacketWrapper packet, InteractionHand hand, @Nullable Vec3 vector + ) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.isAttack(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND, + vector != null ? new Vector(vector.x, vector.y, vector.z) : null + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..c5463b6 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,75 @@ +package com.ticxo.modelengine.v1_21_R3.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper implements Packet { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + private final boolean isAttack; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, int action, ServerboundInteractPacket original) { + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + this.isAttack = action == 1; + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_INTERACT; + } + + public int getEntityId() { + return this.originalId; + } + + public boolean isAttack() { + return this.isAttack; + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/BulkEntityDataEncoder.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..9d48423 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R3.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/Bundler.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/Bundler.java new file mode 100644 index 0000000..e20a27c --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_21_R3.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.getLast(); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection> packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.getLast(); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet packet : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/NetworkUtils.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/NetworkUtils.java new file mode 100644 index 0000000..9424f5a --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/NetworkUtils.java @@ -0,0 +1,343 @@ +package com.ticxo.modelengine.v1_21_R3.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R3.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R3.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static final ProtocolInfo CLIENTBOUND_CODEC = GameProtocols.CLIENTBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + public static final ProtocolInfo SERVERBOUND_CODEC = GameProtocols.SERVERBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + private static final Map, Constructor> PACKET_CONSTRUCTOR = new HashMap<>(); + + public static RegistryFriendlyByteBuf createByteBuf() { + return new RegistryFriendlyByteBuf(Unpooled.buffer(), MinecraftServer.getServer().registryAccess()); + } + + public static RegistryFriendlyByteBuf createByteBuf(Consumer consumer) { + RegistryFriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static > T create(Class clazz, RegistryFriendlyByteBuf buf) { + Constructor constructor = PACKET_CONSTRUCTOR.computeIfAbsent(clazz, aClass -> { + try { + Constructor c = aClass.getDeclaredConstructor(RegistryFriendlyByteBuf.class); + c.setAccessible(true); + return c; + } catch (NoSuchMethodException var4x) { + try { + Constructor cx = aClass.getDeclaredConstructor(FriendlyByteBuf.class); + cx.setAccessible(true); + return cx; + } catch (NoSuchMethodException var3) { + throw new RuntimeException(var3); + } + } + }); + + try { + return (T)constructor.newInstance(buf); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException var4) { + throw new RuntimeException(var4); + } + } + + public static FriendlyByteBuf readServerbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + SERVERBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static FriendlyByteBuf readClientbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + CLIENTBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createCameraPivotSpawn(int id, UUID uuid, Vector3f pos, float height) { + ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket( + id, uuid, pos.x, pos.y - height, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createCameraPivotTeleport(int id, Vector3f pos, float height) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - height, pos.z); + ClientboundEntityPositionSyncPacket packet = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - 0.375, pos.z); + ClientboundEntityPositionSyncPacket tpHigher = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + container = EntityContainer.of(id); + container.setId(id); + container.setPosRaw(pos.x, pos.y - 0.5, pos.z); + ClientboundEntityPositionSyncPacket tpLower = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Object createCameraPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos, float height) { + if (codec == null) { + return createCameraPivotTeleport(id, pos, height); + } else { + return switch (codec.update(pos.x, pos.y - height, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createCameraPivotTeleport(id, pos, height); + }; + } + } + + public static Packets.PacketSupplier lodWrapper( + ModeledEntity modeledEntity, BiFunction> packetFunction + ) { + return uuid -> { + AnimationLODHandler.LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/PacketInterceptor.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..17a6e2e --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/PacketInterceptor.java @@ -0,0 +1,84 @@ +package com.ticxo.modelengine.v1_21_R3.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor

    { + private final Map>, PacketInterceptor

    .Modifier>> registry = Maps.newConcurrentMap(); + private final Map>, PacketInterceptor

    .Listener>> postRegistry = Maps.newConcurrentMap(); + + public > PacketInterceptor

    register(Class clazz, Function> function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public > PacketInterceptor

    registerPost(Class clazz, Function>> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor

    .Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection> acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor

    .Listener listener = this.postRegistry.get(original.getClass()); + return (Collection>)(listener != null ? listener.listen(original) : List.of()); + } + } + + class Listener> { + private final Class clazz; + private final Function>> function; + + public Collection> listen(Packet original) { + try { + Collection> collection = this.function.apply(this.clazz.cast(original)); + return (Collection>)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(final Class clazz, final Function>> function) { + this.clazz = clazz; + this.function = function; + } + } + + class Modifier> { + private final Class clazz; + private final Function> function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(final Class clazz, final Function> function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/Packets.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/Packets.java new file mode 100644 index 0000000..ac101dc --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_21_R3.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/HeldItemParser.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..a6a8f8f --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/HeldItemParser.java @@ -0,0 +1,181 @@ +package com.ticxo.modelengine.v1_21_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R3.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapToInt(HeldItemRenderer.Item::getId)) + )) + ); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Map items = renderer.getRendered(); + IntArrayList entityIds = IntArrayList.toList(items.values().stream().mapToInt(HeldItemRenderer.Item::getId)); + entityIds.add(renderer.getId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + return new ClientboundSetEntityDataPacket(renderer.getId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, HeldItemRenderer.Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(HeldItemRenderer.Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(11); + if (spawn) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, this.viewRange)); + } else if (renderer.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + renderer.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), spawn); + renderer.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), spawn); + renderer.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + renderer.getModel() + .ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + renderer.getDisplay() + .ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getId(), entityData); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location loc = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(loc.getX(), loc.getY(), loc.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + EntityContainer container = EntityContainer.of(renderer.getId()); + container.setPosRaw(loc.getX(), loc.getY(), loc.getZ()); + return new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getId(), renderer.getPassengers())); + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/LeashParser.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/LeashParser.java new file mode 100644 index 0000000..a137ecd --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/LeashParser.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.v1_21_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Map leashes = renderer.getRendered(); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(IntArrayList.toList(leashes.values().stream().mapMultiToInt((leash, intConsumer) -> { + intConsumer.accept(leash.getLeashId()); + intConsumer.accept(leash.getPivotId()); + })))); + } + } + + private Packets.PacketSupplier pivotSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + + private ClientboundAddEntityPacket leashSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y - 0.45, pos.z - 0.2, 0.0F, 0.0F, EntityType.BAT, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetEntityDataPacket leashData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getLeashId(), EntityUtils.DEFAULT_BAT_DATA); + } + + private ClientboundSetPassengersPacket mount(LeashRenderer.Leash renderer) { + ArrayList passengers = new ArrayList<>(1); + passengers.add(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), passengers)); + } + + private Object move(LeashRenderer.Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + } + + private ClientboundSetEntityLinkPacket link(LeashRenderer.Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(EntityContainer.of(renderer.getLeashId()), EntityContainer.of(renderer.getConnected().get())); + } + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/MountParser.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/MountParser.java new file mode 100644 index 0000000..53bbe76 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/MountParser.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.v1_21_R3.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R3.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getMountId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Collection mounts = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(mounts.size() * 2); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getMountId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(MountRenderer.Mount renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket mountSpawn(MountRenderer.Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getMountId())); + } + + private ClientboundSetPassengersPacket mount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getMountId(), renderer.getPassengers())); + } + + private Packets.PacketSupplier pivotMove(MountRenderer.Mount renderer) { + return NetworkUtils.createPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(MountRenderer.Mount renderer) { + return new Rot(renderer.getMountId(), renderer.getYaw().get(), (byte)0, false); + } + + private ClientboundSetEntityDataPacket mountHealth(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, renderer.getHealth().get()))); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(MountRenderer.Mount renderer) { + AttributeInstance attributeInstance = new AttributeInstance(Attributes.MAX_HEALTH, onDirty -> {}); + attributeInstance.setBaseValue(renderer.getMaxHealth().get().floatValue()); + return new ClientboundUpdateAttributesPacket(renderer.getMountId(), Lists.newArrayList(new AttributeInstance[]{attributeInstance})); + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/NameTagParser.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..dc11213 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/NameTagParser.java @@ -0,0 +1,184 @@ +package com.ticxo.modelengine.v1_21_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Component.Serializer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTagRenderer.NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTagRenderer.NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Collection nameTags = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(nameTags.size() * 2); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + return !spawn ? null : new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTagRenderer.NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(7); + renderer.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + renderer.getTranslate().ifDirty(flag -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getScale().ifDirty(flag -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getTextOpacity().ifDirty(flag -> entityData.add(new DataValue(26, EntityDataSerializers.BYTE, flag)), spawn); + renderer.getBackgroundColor().ifDirty(flag -> entityData.add(new DataValue(25, EntityDataSerializers.INT, flag)), spawn); + renderer.getStyle().ifDirty(flags -> entityData.add(new DataValue(27, EntityDataSerializers.BYTE, flags)), spawn); + renderer.getLineWidth().ifDirty(flag -> entityData.add(new DataValue(24, EntityDataSerializers.INT, flag)), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new MatchException(null, null); + }; + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, value)); + }, spawn); + renderer.getJsonString() + .ifDirty( + jsonString -> { + if (jsonString == null) { + entityData.add(new DataValue(23, EntityDataSerializers.COMPONENT, Component.empty())); + } else { + entityData.add( + new DataValue(23, EntityDataSerializers.COMPONENT, Serializer.fromJson(jsonString, MinecraftServer.getServer().registryAccess())) + ); + } + }, + spawn + ); + renderer.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getTagId(), entityData); + } + } + + private Object pivotMove(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTagRenderer.NameTag renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getTagId())); + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/SegmentParser.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..daf2c27 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/SegmentParser.java @@ -0,0 +1,205 @@ +package com.ticxo.modelengine.v1_21_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R3.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (SegmentRenderer.Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + IntArrayList destroy = new IntArrayList(); + + for (SegmentRenderer.Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(destroy))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(SegmentRenderer.Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SegmentRenderer.Pivot pivot) { + return new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(SegmentRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(SegmentRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(SegmentRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + ArrayList> entityData = new ArrayList<>(13); + if (force) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } else if (bone.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : 1)), force); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), force); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/SubHitboxParser.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..8aa1327 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/behavior/SubHitboxParser.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R3.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitboxRenderer.SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Collection subHitboxes = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(subHitboxes.size() * 2); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private Object pivotMove(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getHitboxId())); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitboxRenderer.SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitboxRenderer.SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(4); + renderer.getWidth().ifDirty(width -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, width)), spawn); + renderer.getHeight().ifDirty(height -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, height)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getHitboxId(), entityData); + } + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/model/DisplayParser.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/model/DisplayParser.java new file mode 100644 index 0000000..51a6be2 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/model/DisplayParser.java @@ -0,0 +1,789 @@ +package com.ticxo.modelengine.v1_21_R3.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R3.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static StreamCodec CUSTOM_PAYLOAD_CODEC; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + if (renderer.hasGlowAudience()) { + this.updateAudienceGlow(renderer, data.getTracking().keySet(), data.getStartTracking(), this.noCullForcePlayers); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + private void updateAudienceGlow(DisplayRenderer renderer, Set current, Set startTracking, Set forceUpdates) { + for (DisplayBone bone : renderer.getRendered().values()) { + Set audience = bone.getGlowAudience().get(); + if (audience != null) { + boolean changed = bone.isAudienceGlowDirty(); + if (changed || !startTracking.isEmpty() || !forceUpdates.isEmpty()) { + boolean glowing = bone.getAudienceGlowing().get(); + int color = bone.getAudienceGlowColor().get(); + Set on = new HashSet<>(); + Set off = new HashSet<>(); + if (changed) { + for (UUID uuid : current) { + if (glowing && audience.contains(uuid)) { + on.add(uuid); + } else { + off.add(uuid); + } + } + + bone.clearAudienceGlowDirty(); + } else if (glowing) { + for (UUID uuidx : startTracking) { + if (audience.contains(uuidx)) { + on.add(uuidx); + } + } + + for (UUID uuidxx : forceUpdates) { + if (audience.contains(uuidxx)) { + on.add(uuidxx); + } + } + } + + if (!on.isEmpty() || !off.isEmpty()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + int id = boneData.getId(); + if (!on.isEmpty()) { + NetworkUtils.send(on, this.audienceGlowData(id, true, color)); + } + + if (!off.isEmpty()) { + NetworkUtils.send(off, this.audienceGlowData(id, false, color)); + } + } + } + } + } + } + } + + private ClientboundSetEntityDataPacket audienceGlowData(int entityId, boolean glowing, int color) { + ArrayList> entityData = new ArrayList<>(2); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(glowing ? 96 : 32))); + if (glowing) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + + return new ClientboundSetEntityDataPacket(entityId, entityData); + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + set.add((Packet)this.pivotCameraResize(pivot)); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(destroy)))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(hitboxDestroy)))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)(u -> this.displayData(u, null, boneData, false, transformOnly))); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + AnimationLODHandler.LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + RegistryFriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(RegistryFriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CODEC == null) { + Field field = ClientboundCustomPayloadPacket.class.getField("GAMEPLAY_STREAM_CODEC"); + field.setAccessible(true); + CUSTOM_PAYLOAD_CODEC = (StreamCodec)field.get(null); + } + + return (Packet)CUSTOM_PAYLOAD_CODEC.decode(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData( + BulkEntityDataEncoder encoder, + UUID uuid, + @Nullable AnimationLODHandler.LODTracker tracker, + DisplayBone.BoneData boneData, + boolean force, + boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? new ClientboundSetEntityDataPacket(pivot.getId(), this.cameraPivotData(pivot.getCameraHeight().get())) + : new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private List> cameraPivotData(float height) { + return List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(8, EntityDataSerializers.FLOAT, 0.0F), + new DataValue(9, EntityDataSerializers.FLOAT, height) + ); + } + + private ClientboundSetPassengersPacket pivotMount(DisplayRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(DisplayRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundSetEntityDataPacket pivotCameraResize(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() && pivot.getCameraHeight().isDirty() + ? new ClientboundSetEntityDataPacket(pivot.getId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, pivot.getCameraHeight().get()))) + : null; + } + + private ClientboundAddEntityPacket displaySpawn(DisplayRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData( + UUID uuid, @Nullable AnimationLODHandler.LODTracker tracker, DisplayBone.BoneData boneData, boolean force, boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + ArrayList> entityData = new ArrayList<>(13); + if (!force && update != 0) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : lodTick)), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + entityData.add(new DataValue(16, EntityDataSerializers.INT, val)); + } + }, force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + } + }, force); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + + private ClientboundSetEntityDataPacket displayVisibleData(DisplayBone.BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)))); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color))); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val))); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F))); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)))); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()))); + this.cleanupQueue.add(bone::clearDirty); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(DisplayRenderer.Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(DisplayRenderer.Hitbox hitbox) { + return !hitbox.isPivotVisible() ? null : new ClientboundSetEntityDataPacket(hitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket hitboxSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(4); + hitbox.getWidth().ifDirty(val -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, val)), spawn); + hitbox.getHeight().ifDirty(val -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getHitboxId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(2); + hitbox.getShadowRadius().ifDirty(val -> entityData.add(new DataValue(18, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getShadowId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(DisplayRenderer.Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(DisplayRenderer.Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + return new ClientboundSetPassengersPacket(EntityContainer.of(hitbox.getPivotId(), passengers)); + } + } +} diff --git a/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/vfx/VFXDisplayParser.java b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..ff773e6 --- /dev/null +++ b/nms/v1_21_R3/src/main/java/com/ticxo/modelengine/v1_21_R3/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,124 @@ +package com.ticxo.modelengine.v1_21_R3.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R3.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R3.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R3.network.utils.Packets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(new int[]{vfx.getPivotId(), vfx.getModelId()})); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXDisplayRenderer.VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetEntityDataPacket(vfx.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXDisplayRenderer.VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXDisplayRenderer.VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(9); + if (spawn) { + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)32)); + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, 4096.0F)); + entityData.add(new DataValue(24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal())); + } else if (vfx.isModelDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + vfx.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + vfx.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + vfx.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + vfx.clearModelDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(vfx.getModelId(), entityData); + } + } + + private Object teleport(VFXDisplayRenderer.VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetPassengersPacket(EntityContainer.of(vfx.getPivotId(), vfx.getModelId())); + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSFields.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSFields.java new file mode 100644 index 0000000..f7bf602 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSFields.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_21_R4; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionUtils.ReflectionEnum { + ENTITY_dimensions(Entity.class, "be", "dimensions"), + ENTITY_eyeHeight(Entity.class, "bf", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "bQ", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "bf", "jumping"), + MOB_lookControl(Mob.class, "bB", "lookControl"), + MOB_moveControl(Mob.class, "bC", "moveControl"), + MOB_navigation(Mob.class, "bE", "navigation"), + MOB_goalSelector(Mob.class, "bF", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "bN", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "I", "clientIsFloating"), + SERVER_COMMON_PACKET_LISTENER_IMPL_connection(ServerCommonPacketListenerImpl.class, "e", "connection"), + MOVE_CONTROL_operation(MoveControl.class, "k", "operation"), + TRACKED_ENTITY_serverEntity(TrackedEntity.class, "b", "serverEntity"), + TRACKED_ENTITY_range(TrackedEntity.class, "d", "range"), + LEVEL_threadSafeRandom(Level.class, "f", "threadSafeRandom"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "a", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "b", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(final Class target, final String obfuscated, final String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSHandler_v1_21_R4.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSHandler_v1_21_R4.java new file mode 100644 index 0000000..1a7e6fb --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSHandler_v1_21_R4.java @@ -0,0 +1,231 @@ +package com.ticxo.modelengine.v1_21_R4; + +import com.mojang.math.MatrixUtil; +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.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_21_R4.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R4.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_21_R4.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_21_R4.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_21_R4.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_21_R4.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_21_R4.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_21_R4.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.components.CustomModelDataComponent; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_21_R4 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + private boolean manualTranslucencyOrder; + private boolean forceCMD; + + public NMSHandler_v1_21_R4() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + public void updateConfig() { + this.manualTranslucencyOrder = ConfigProperty.MANUAL_TRANSLUCENCY_ORDER.getBoolean(); + this.forceCMD = ConfigProperty.FORCE_CMD.getBoolean(); + } + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + RegistryFriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, NetworkUtils.create(ClientboundSetPassengersPacket.class, byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public Set createStack(ItemModelData data, ItemModelData.Context context) { + if (this.forceCMD) { + return NMSHandler.super.createStack(data, context); + } else { + ItemStack item = new ItemStack(this.manualTranslucencyOrder && !data.isTranslucent() ? Material.GLASS : Material.BONE); + item.editMeta(itemMeta -> { + itemMeta.setItemModel(data.getSingleComposite().model()); + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(context.color())); + if (data.getVariant() != null) { + cmdComp.setStrings(List.of(data.getVariant())); + } + + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return Set.of(item); + } + } + + @Override + public boolean colorStack(ItemStack stack, Color color) { + stack.editMeta(itemMeta -> { + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(color)); + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return true; + } + + @Override + public void applyPlayerHeadItemModel(ItemStack stack) { + stack.editMeta(meta -> meta.setItemModel(this.getPlayerHeadModelKey())); + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(EntityContainer.of(mountId, passengerIds)); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSMethods.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSMethods.java new file mode 100644 index 0000000..2937238 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/NMSMethods.java @@ -0,0 +1,49 @@ +package com.ticxo.modelengine.v1_21_R4; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.core.HolderLookup.Provider; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements ReflectionUtils.MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "i", "getInstrument", ItemStack.class, Provider.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityContainer.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityContainer.java new file mode 100644 index 0000000..6cc7e68 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityContainer.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_21_R4.entity; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.syncher.SynchedEntityData.Builder; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.ApiStatus.Internal; + +@Internal +public class EntityContainer extends Entity { + public static EntityContainer of(int id) { + return new EntityContainer(id); + } + + public static Entity of(int id, int... passengerIds) { + EntityContainer container = of(id); + container.setPassengers(Arrays.stream(passengerIds).mapToObj(EntityContainer::new).toList()); + return container; + } + + public static Entity of(int id, Collection passengerIds) { + EntityContainer container = of(id); + container.setPassengers(passengerIds.stream().map(EntityContainer::new).toList()); + return container; + } + + private EntityContainer(int id) { + super(EntityType.INTERACTION, MinecraftServer.getServer().overworld()); + this.setId(id); + this.setPosRaw(0.0, 0.0, 0.0); + this.setRot(0.0F, 0.0F); + this.setOnGround(false); + } + + protected void setPassengers(List passengers) { + this.passengers = ImmutableList.copyOf(passengers); + } + + protected void defineSynchedData(@NotNull Builder builder) { + } + + public boolean hurtServer(ServerLevel world, DamageSource source, float amount) { + return false; + } + + protected void readAdditionalSaveData(@NotNull CompoundTag nbt) { + } + + protected void addAdditionalSaveData(@NotNull CompoundTag nbt) { + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityHandlerImpl.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..f3bb9d9 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityHandlerImpl.java @@ -0,0 +1,742 @@ +package com.ticxo.modelengine.v1_21_R4.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_21_R4.NMSFields; +import com.ticxo.modelengine.v1_21_R4.NMSMethods; +import com.ticxo.modelengine.v1_21_R4.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_21_R4.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_21_R4.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_21_R4.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_21_R4.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_21_R4.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_21_R4.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R4.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_21_R4.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R4.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.minecraft.core.Holder; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult.Fail; +import net.minecraft.world.InteractionResult.Pass; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.TryEmptyHandInteraction; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityAttachments; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemUseAnimation; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + float width = (float)hitbox.getMaxWidth(); + float height = (float)hitbox.getHeight(); + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions(width, height, (float)hitbox.getEyeHeight(), EntityAttachments.createDefault(width, height), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + if (EntityUtils.nms(entity) instanceof LivingEntity living) { + living.getAttributes().registerAttribute(Attributes.STEP_HEIGHT); + Objects.requireNonNull(living.getAttribute(Attributes.STEP_HEIGHT)).setBaseValue(height); + } + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityType.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y - nmsEntity.getVehicleAttachmentPoint(this.dummyArmorStand).y; + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + entity.getEntityId(), List.of(new DataValue(0, EntityDataSerializers.BYTE, data)) + ); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + switch (oldNav) { + case WallClimberNavigation wallClimberNavigation: + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + break; + case GroundPathNavigation groundPathNavigation: + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + break; + case FlyingPathNavigation flyingPathNavigation: + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + break; + case WaterBoundPathNavigation waterBoundPathNavigation: + newNav = new WaterBoundNavigationWrapper(mob); + break; + case AmphibiousPathNavigation amphibiousPathNavigation: + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + break; + default: + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var13) { + var13.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + ServerLevel level = ((CraftWorld)location.getWorld()).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity.level() instanceof ServerLevel worldserver) { + return nmsEntity.hurtServer(worldserver, damageSource, amount); + } + } + + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + + @Override + public EntityHandler.InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case Success success -> success.equals(net.minecraft.world.InteractionResult.SUCCESS_SERVER) + ? EntityHandler.InteractionResult.SUCCESS + : ( + success.equals(net.minecraft.world.InteractionResult.SUCCESS) + ? EntityHandler.InteractionResult.CONSUME_PARTIAL + : EntityHandler.InteractionResult.CONSUME + ); + case TryEmptyHandInteraction ignored -> EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED; + case Pass ignoredx -> EntityHandler.InteractionResult.PASS; + case Fail ignoredxx -> EntityHandler.InteractionResult.FAIL; + default -> throw new MatchException(null, null); + }; + } else { + return EntityHandler.InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket( + DynamicHitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA + ); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(DynamicHitbox.getHitboxId(), EntityUtils.DEFAULT_SLIME_DATA); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket( + EntityContainer.of(DynamicHitbox.getPivotId(), DynamicHitbox.getHitboxId()) + ); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0, 0.0F, 0.0F + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != ItemUseAnimation.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + player.getEntityId(), List.of(new DataValue(8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3))) + ); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call( + instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack, nmsPlayer.registryAccess() + ); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public Float getCameraEyeHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return nmsEntity.getDimensions(Pose.STANDING).eyeHeight(); + } + + @Override + public Float getCameraPivotHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + EntityDimensions dimensions = nmsEntity.getDimensions(nmsEntity.getPose()); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 attachment = ReflectionUtils.call(nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, dimensions, 1.0F); + return attachment == null ? null : (float)(dimensions.eyeHeight() - attachment.y); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = level.getChunkSource().chunkMap.entityMap; + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = lvl.getChunkSource().chunkMap.entityMap; + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + EntityHandler.BoxRelToCam relX = EntityHandler.BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + EntityHandler.BoxRelToCam relY = EntityHandler.BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + EntityHandler.BoxRelToCam relZ = EntityHandler.BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == EntityHandler.BoxRelToCam.INSIDE && relY == EntityHandler.BoxRelToCam.INSIDE && relZ == EntityHandler.BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.DUST, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityMetadataID.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityMetadataID.java new file mode 100644 index 0000000..ea4b431 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityMetadataID.java @@ -0,0 +1,36 @@ +package com.ticxo.modelengine.v1_21_R4.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityUtils.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityUtils.java new file mode 100644 index 0000000..4e7a8b7 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/EntityUtils.java @@ -0,0 +1,30 @@ +package com.ticxo.modelengine.v1_21_R4.entity; + +import java.util.List; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.entity.CraftEntity; + +public class EntityUtils { + public static final List> DEFAULT_AREA_EFFECT_CLOUD_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(8, EntityDataSerializers.FLOAT, 0.0F) + ); + public static final List> DEFAULT_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(16, EntityDataSerializers.INT, 2) + ); + public static final List> DEFAULT_BAT_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE) + ); + public static final List> DEFAULT_ARMOR_STAND_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(15, EntityDataSerializers.BYTE, (byte)16) + ); + + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/OcclusionClipContext.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/OcclusionClipContext.java new file mode 100644 index 0000000..795eba6 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v1_21_R4.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape() == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (!(tX <= 1.0) && !(tY <= 1.0) && !(tZ <= 1.0)) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/TrackedEntityImpl.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..cd8aacc --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/TrackedEntityImpl.java @@ -0,0 +1,286 @@ +package com.ticxo.modelengine.v1_21_R4.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R4.NMSFields; +import com.ticxo.modelengine.v1_21_R4.NMSMethods; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } + + @Override + public boolean isViewerSetUnchanged() { + if ((!this.mayHaveForced || this.forcedPairing.isEmpty() && this.forcedRemove.isEmpty()) && this.playerPredicate == DEFAULT_PREDICATE) { + if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } else { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/BodyRotationControlWrapper.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..8fa10a5 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_21_R4.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/LookControlWrapper.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..0ad194e --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/LookControlWrapper.java @@ -0,0 +1,152 @@ +package com.ticxo.modelengine.v1_21_R4.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import io.papermc.paper.entity.activation.ActivationRange; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + private MovementOverride movementOverride; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateDirection(this, this.modeledEntity); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/MoveControlWrapper.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..a73618f --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/controller/MoveControlWrapper.java @@ -0,0 +1,272 @@ +package com.ticxo.modelengine.v1_21_R4.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R4.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.Input; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + protected MovementOverride movementOverride; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateMovement(this, modeledEntity); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + if (entity instanceof Player player) { + Input playerInput = player.getCurrentInput(); + controller.setInput( + new MountController.MountInput( + playerInput.isForward(), + playerInput.isBackward(), + playerInput.isLeft(), + playerInput.isRight(), + playerInput.isJump(), + playerInput.isSneak(), + playerInput.isSprint() + ) + ); + } else { + controller.setInput(new MountController.MountInput()); + } + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/hitbox/HitboxEntityImpl.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..7c78856 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,271 @@ +package com.ticxo.modelengine.v1_21_R4.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_21_R4.NMSFields; +import com.ticxo.modelengine.v1_21_R4.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + @NotNull + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public boolean isInvisible() { + return true; + } + + public void push(@NotNull Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox(Vec3 position) { + if (this.subHitbox == null) { + return super.makeBoundingBox(position); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(@NotNull Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurtServer(@NotNull ServerLevel world, @NotNull DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurtServer(world, source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + BaseEntity baseEntity = this.bone.getActiveModel().getModeledEntity().getBase(); + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return baseEntity.hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, @NotNull InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, entity, new Vector(0, 0, 0), hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact(this, player.getBukkitEntity(), hand == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND); + + return (InteractionResult)(switch (result) { + case SUCCESS -> InteractionResult.SUCCESS_SERVER; + case SUCCESS_NO_ITEM_USED -> InteractionResult.TRY_WITH_EMPTY_HAND; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.SUCCESS; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }); + } + } + + public boolean shouldBeSaved() { + return false; + } + + @NotNull + public CraftEntity getBukkitEntity() { + CraftEntity bukkitEntity = this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + CraftEntity var5 = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(var5); + return var5; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(@NotNull RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/hitbox/OBB.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/hitbox/OBB.java new file mode 100644 index 0000000..664cc5b --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R4.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..694ce8a --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R4.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..2a1277e --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R4.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/GroundNavigationWrapper.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..5ed71bf --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R4.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..58cfca0 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R4.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..5584ecf --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_21_R4.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/ModelEngineChannelHandler.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..e38a51a --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/ModelEngineChannelHandler.java @@ -0,0 +1,457 @@ +package com.ticxo.modelengine.v1_21_R4.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R4.NMSFields; +import com.ticxo.modelengine.v1_21_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R4.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntList; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundEntityPositionSyncPacket.class, this::handlePositionSync) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove) + .register(ServerboundClientTickEndPacket.class, this::handleClientTickEnd); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet rawPacket && asClientPacket(rawPacket) instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + Collection> post = this.writeInterceptors.acceptPost(result); + if (!post.isEmpty()) { + list.addAll(post); + } + } + } + + if (!list.isEmpty()) { + Packet var12 = new ClientboundBundlePacket(list); + super.write(ctx, var12, promise); + } + } else { + Packet var13 = this.writeInterceptors.accept(packet); + if (var13 == null) { + return; + } + + Collection> post = this.writeInterceptors.acceptPost(var13); + if (post.isEmpty()) { + super.write(ctx, var13, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var13); + list.addAll(post); + Packet var14 = new ClientboundBundlePacket(list); + super.write(ctx, var14, promise); + } + } + } catch (Throwable var11) { + var11.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List> handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List> handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + List> list = null; + Optional maybeMount = model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT); + if (maybeMount.isPresent() && maybeMount.get() instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + MountRenderer.Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + if (mount == null) { + return null; + } + + CollectionDataTracker ids = mount.getPassengers(); + list = new ArrayList<>(); + list.add(new ClientboundSetPassengersPacket(EntityContainer.of(mount.getMountId(), ids))); + } + } + + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + IntList ids = packet.getEntityIds(); + + for (int i = 0; i < ids.size(); i++) { + this.markViewersDirty(ids.getInt(i)); + } + + int[] set = packet.getEntityIds().intStream().filter(id -> ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE).toArray(); + return set.length == packet.getEntityIds().size() ? packet : new ClientboundRemoveEntitiesPacket(IntArrayList.wrap(set)); + } + + private > T handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readClientbound(packet); + + Packet var4; + try { + int id = buf.readVarInt(); + var4 = ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } finally { + buf.release(); + } + + return (T)var4; + } + + private > T handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundEntityPositionSyncPacket handlePositionSync(ClientboundEntityPositionSyncPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + int id = packet.entityId(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + return !changed ? packet : new ClientboundSetPassengersPacket(EntityContainer.of(packet.getVehicle(), new IntArrayList(merged))); + } + } + } + + private Packet handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readServerbound(packet); + + int entityId; + int action; + try { + entityId = buf.readVarInt(); + action = buf.readVarInt(); + } finally { + buf.release(); + } + + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), action, packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, action, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, action, packet) : packet); + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountController.MountInput input = controller.getInput(); + if (input == null) { + controller.setInput( + new MountController.MountInput( + inputPacket.input().forward(), + inputPacket.input().backward(), + inputPacket.input().left(), + inputPacket.input().right(), + inputPacket.input().jump(), + inputPacket.input().shift(), + inputPacket.input().sprint() + ) + ); + } else { + input.setForward(inputPacket.input().forward()); + input.setBackward(inputPacket.input().backward()); + input.setLeft(inputPacket.input().left()); + input.setRight(inputPacket.input().right()); + input.setJump(inputPacket.input().jump()); + input.setSneak(inputPacket.input().shift()); + input.setSprint(inputPacket.input().sprint()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + if (!ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + private ServerboundClientTickEndPacket handleClientTickEnd(ServerboundClientTickEndPacket packet) { + if (ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + @SuppressWarnings("unchecked") + private static Packet asClientPacket(Object packet) { + return (Packet)packet; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/NetworkHandlerImpl.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..1d88ebc --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/NetworkHandlerImpl.java @@ -0,0 +1,141 @@ +package com.ticxo.modelengine.v1_21_R4.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R4.NMSFields; +import com.ticxo.modelengine.v1_21_R4.network.utils.Bundler; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection> collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/patch/PatchedServerGamePacketListener.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..76ee140 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,439 @@ +package com.ticxo.modelengine.v1_21_R4.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R4.NMSMethods; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.SwingSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(final ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().serverLevel()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.serverLevel(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + ModelBone hitBone = null; + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel == null) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(interactPacket.getRelayedId()); + if (hitbox != null) { + hitBone = hitbox.getBone(); + activeModel = hitBone.getActiveModel(); + } + } + + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + final ActiveModel finalActiveModel = activeModel; + final ModelBone finalHitBone = hitBone; + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + null, + finalHitBone + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + position, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + position, + finalHitBone + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.ATTACK, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, null); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, pos); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent( + craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND, null + ); + } + } + ); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= player.entityInteractionRange() * player.entityInteractionRange())) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelectedItem().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem)) { + if (player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + ServerEntity serverEntity = entity.moonrise$getTrackedEntity().serverEntity; + List> list = new ArrayList<>(); + serverEntity.sendPairingData(player, list::add); + player.connection.send(new ClientboundBundlePacket(list)); + } + + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem) { + List> data = entity.getEntityData().packAll(); + if (data != null && player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + player.connection.send(new ClientboundSetEntityDataPacket(entity.getId(), data)); + } + + if (entity instanceof Allay allay) { + List> equipment = Arrays.stream(EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.getItemBySlot(slot))) + .collect(Collectors.toList()); + connection.send(new ClientboundSetEquipmentPacket(entity.getId(), equipment)); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.serverLevel()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.serverLevel(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level().clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.isSameItemSameComponents(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand, + movingobjectpositionblock.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, itemstack, enumhand); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.resyncUsingItem(player); + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent( + CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacketWrapper packet, InteractionHand hand, @Nullable Vec3 vector + ) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.isAttack(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND, + vector != null ? new Vector(vector.x, vector.y, vector.z) : null + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..631795a --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,75 @@ +package com.ticxo.modelengine.v1_21_R4.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper implements Packet { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + private final boolean isAttack; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, int action, ServerboundInteractPacket original) { + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + this.isAttack = action == 1; + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_INTERACT; + } + + public int getEntityId() { + return this.originalId; + } + + public boolean isAttack() { + return this.isAttack; + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/BulkEntityDataEncoder.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..28f4291 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R4.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/Bundler.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/Bundler.java new file mode 100644 index 0000000..6620501 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_21_R4.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.getLast(); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection> packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.getLast(); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet packet : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/NetworkUtils.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/NetworkUtils.java new file mode 100644 index 0000000..e0b6a98 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/NetworkUtils.java @@ -0,0 +1,344 @@ +package com.ticxo.modelengine.v1_21_R4.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R4.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.GameProtocols.Context; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static final ProtocolInfo CLIENTBOUND_CODEC = GameProtocols.CLIENTBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + public static final ProtocolInfo SERVERBOUND_CODEC = GameProtocols.SERVERBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess()), (Context)() -> false); + private static final Map, Constructor> PACKET_CONSTRUCTOR = new HashMap<>(); + + public static RegistryFriendlyByteBuf createByteBuf() { + return new RegistryFriendlyByteBuf(Unpooled.buffer(), MinecraftServer.getServer().registryAccess()); + } + + public static RegistryFriendlyByteBuf createByteBuf(Consumer consumer) { + RegistryFriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static > T create(Class clazz, RegistryFriendlyByteBuf buf) { + Constructor constructor = PACKET_CONSTRUCTOR.computeIfAbsent(clazz, aClass -> { + try { + Constructor c = aClass.getDeclaredConstructor(RegistryFriendlyByteBuf.class); + c.setAccessible(true); + return c; + } catch (NoSuchMethodException var4x) { + try { + Constructor cx = aClass.getDeclaredConstructor(FriendlyByteBuf.class); + cx.setAccessible(true); + return cx; + } catch (NoSuchMethodException var3) { + throw new RuntimeException(var3); + } + } + }); + + try { + return (T)constructor.newInstance(buf); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException var4) { + throw new RuntimeException(var4); + } + } + + public static FriendlyByteBuf readServerbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + SERVERBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static FriendlyByteBuf readClientbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + CLIENTBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createCameraPivotSpawn(int id, UUID uuid, Vector3f pos, float height) { + ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket( + id, uuid, pos.x, pos.y - height, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createCameraPivotTeleport(int id, Vector3f pos, float height) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - height, pos.z); + ClientboundEntityPositionSyncPacket packet = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - 0.375, pos.z); + ClientboundEntityPositionSyncPacket tpHigher = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + container = EntityContainer.of(id); + container.setId(id); + container.setPosRaw(pos.x, pos.y - 0.5, pos.z); + ClientboundEntityPositionSyncPacket tpLower = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Object createCameraPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos, float height) { + if (codec == null) { + return createCameraPivotTeleport(id, pos, height); + } else { + return switch (codec.update(pos.x, pos.y - height, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createCameraPivotTeleport(id, pos, height); + }; + } + } + + public static Packets.PacketSupplier lodWrapper( + ModeledEntity modeledEntity, BiFunction> packetFunction + ) { + return uuid -> { + AnimationLODHandler.LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/PacketInterceptor.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..17bfbfa --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/PacketInterceptor.java @@ -0,0 +1,84 @@ +package com.ticxo.modelengine.v1_21_R4.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor

    { + private final Map>, PacketInterceptor

    .Modifier>> registry = Maps.newConcurrentMap(); + private final Map>, PacketInterceptor

    .Listener>> postRegistry = Maps.newConcurrentMap(); + + public > PacketInterceptor

    register(Class clazz, Function> function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public > PacketInterceptor

    registerPost(Class clazz, Function>> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor

    .Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection> acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor

    .Listener listener = this.postRegistry.get(original.getClass()); + return (Collection>)(listener != null ? listener.listen(original) : List.of()); + } + } + + class Listener> { + private final Class clazz; + private final Function>> function; + + public Collection> listen(Packet original) { + try { + Collection> collection = this.function.apply(this.clazz.cast(original)); + return (Collection>)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(final Class clazz, final Function>> function) { + this.clazz = clazz; + this.function = function; + } + } + + class Modifier> { + private final Class clazz; + private final Function> function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(final Class clazz, final Function> function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/Packets.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/Packets.java new file mode 100644 index 0000000..0a8bdcd --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_21_R4.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/HeldItemParser.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..363d6b5 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/HeldItemParser.java @@ -0,0 +1,181 @@ +package com.ticxo.modelengine.v1_21_R4.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapToInt(HeldItemRenderer.Item::getId)) + )) + ); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Map items = renderer.getRendered(); + IntArrayList entityIds = IntArrayList.toList(items.values().stream().mapToInt(HeldItemRenderer.Item::getId)); + entityIds.add(renderer.getId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + return new ClientboundSetEntityDataPacket(renderer.getId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, HeldItemRenderer.Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(HeldItemRenderer.Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(11); + if (spawn) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, this.viewRange)); + } else if (renderer.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + renderer.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), spawn); + renderer.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), spawn); + renderer.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + renderer.getModel() + .ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + renderer.getDisplay() + .ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getId(), entityData); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location loc = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(loc.getX(), loc.getY(), loc.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + EntityContainer container = EntityContainer.of(renderer.getId()); + container.setPosRaw(loc.getX(), loc.getY(), loc.getZ()); + return new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getId(), renderer.getPassengers())); + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/LeashParser.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/LeashParser.java new file mode 100644 index 0000000..c1cb12b --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/LeashParser.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.v1_21_R4.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Map leashes = renderer.getRendered(); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(IntArrayList.toList(leashes.values().stream().mapMultiToInt((leash, intConsumer) -> { + intConsumer.accept(leash.getLeashId()); + intConsumer.accept(leash.getPivotId()); + })))); + } + } + + private Packets.PacketSupplier pivotSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + + private ClientboundAddEntityPacket leashSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y - 0.45, pos.z - 0.2, 0.0F, 0.0F, EntityType.BAT, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetEntityDataPacket leashData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getLeashId(), EntityUtils.DEFAULT_BAT_DATA); + } + + private ClientboundSetPassengersPacket mount(LeashRenderer.Leash renderer) { + ArrayList passengers = new ArrayList<>(1); + passengers.add(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), passengers)); + } + + private Object move(LeashRenderer.Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + } + + private ClientboundSetEntityLinkPacket link(LeashRenderer.Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(EntityContainer.of(renderer.getLeashId()), EntityContainer.of(renderer.getConnected().get())); + } + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/MountParser.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/MountParser.java new file mode 100644 index 0000000..22f3133 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/MountParser.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.v1_21_R4.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getMountId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Collection mounts = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(mounts.size() * 2); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getMountId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(MountRenderer.Mount renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket mountSpawn(MountRenderer.Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getMountId())); + } + + private ClientboundSetPassengersPacket mount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getMountId(), renderer.getPassengers())); + } + + private Packets.PacketSupplier pivotMove(MountRenderer.Mount renderer) { + return NetworkUtils.createPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(MountRenderer.Mount renderer) { + return new Rot(renderer.getMountId(), renderer.getYaw().get(), (byte)0, false); + } + + private ClientboundSetEntityDataPacket mountHealth(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, renderer.getHealth().get()))); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(MountRenderer.Mount renderer) { + AttributeInstance attributeInstance = new AttributeInstance(Attributes.MAX_HEALTH, onDirty -> {}); + attributeInstance.setBaseValue(renderer.getMaxHealth().get().floatValue()); + return new ClientboundUpdateAttributesPacket(renderer.getMountId(), Lists.newArrayList(new AttributeInstance[]{attributeInstance})); + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/NameTagParser.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..ede74dd --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/NameTagParser.java @@ -0,0 +1,184 @@ +package com.ticxo.modelengine.v1_21_R4.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Component.Serializer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTagRenderer.NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTagRenderer.NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Collection nameTags = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(nameTags.size() * 2); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + return !spawn ? null : new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTagRenderer.NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(7); + renderer.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + renderer.getTranslate().ifDirty(flag -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getScale().ifDirty(flag -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getTextOpacity().ifDirty(flag -> entityData.add(new DataValue(26, EntityDataSerializers.BYTE, flag)), spawn); + renderer.getBackgroundColor().ifDirty(flag -> entityData.add(new DataValue(25, EntityDataSerializers.INT, flag)), spawn); + renderer.getStyle().ifDirty(flags -> entityData.add(new DataValue(27, EntityDataSerializers.BYTE, flags)), spawn); + renderer.getLineWidth().ifDirty(flag -> entityData.add(new DataValue(24, EntityDataSerializers.INT, flag)), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new MatchException(null, null); + }; + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, value)); + }, spawn); + renderer.getJsonString() + .ifDirty( + jsonString -> { + if (jsonString == null) { + entityData.add(new DataValue(23, EntityDataSerializers.COMPONENT, Component.empty())); + } else { + entityData.add( + new DataValue(23, EntityDataSerializers.COMPONENT, Serializer.fromJson(jsonString, MinecraftServer.getServer().registryAccess())) + ); + } + }, + spawn + ); + renderer.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getTagId(), entityData); + } + } + + private Object pivotMove(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTagRenderer.NameTag renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getTagId())); + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/SegmentParser.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..d2444c9 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/SegmentParser.java @@ -0,0 +1,205 @@ +package com.ticxo.modelengine.v1_21_R4.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (SegmentRenderer.Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + IntArrayList destroy = new IntArrayList(); + + for (SegmentRenderer.Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(destroy))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(SegmentRenderer.Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SegmentRenderer.Pivot pivot) { + return new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(SegmentRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(SegmentRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(SegmentRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + ArrayList> entityData = new ArrayList<>(13); + if (force) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } else if (bone.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : 1)), force); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), force); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/SubHitboxParser.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..a699d89 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/behavior/SubHitboxParser.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R4.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitboxRenderer.SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Collection subHitboxes = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(subHitboxes.size() * 2); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private Object pivotMove(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getHitboxId())); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitboxRenderer.SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitboxRenderer.SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(4); + renderer.getWidth().ifDirty(width -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, width)), spawn); + renderer.getHeight().ifDirty(height -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, height)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getHitboxId(), entityData); + } + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/model/DisplayParser.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/model/DisplayParser.java new file mode 100644 index 0000000..2627da2 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/model/DisplayParser.java @@ -0,0 +1,789 @@ +package com.ticxo.modelengine.v1_21_R4.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static StreamCodec CUSTOM_PAYLOAD_CODEC; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + if (renderer.hasGlowAudience()) { + this.updateAudienceGlow(renderer, data.getTracking().keySet(), data.getStartTracking(), this.noCullForcePlayers); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + private void updateAudienceGlow(DisplayRenderer renderer, Set current, Set startTracking, Set forceUpdates) { + for (DisplayBone bone : renderer.getRendered().values()) { + Set audience = bone.getGlowAudience().get(); + if (audience != null) { + boolean changed = bone.isAudienceGlowDirty(); + if (changed || !startTracking.isEmpty() || !forceUpdates.isEmpty()) { + boolean glowing = bone.getAudienceGlowing().get(); + int color = bone.getAudienceGlowColor().get(); + Set on = new HashSet<>(); + Set off = new HashSet<>(); + if (changed) { + for (UUID uuid : current) { + if (glowing && audience.contains(uuid)) { + on.add(uuid); + } else { + off.add(uuid); + } + } + + bone.clearAudienceGlowDirty(); + } else if (glowing) { + for (UUID uuidx : startTracking) { + if (audience.contains(uuidx)) { + on.add(uuidx); + } + } + + for (UUID uuidxx : forceUpdates) { + if (audience.contains(uuidxx)) { + on.add(uuidxx); + } + } + } + + if (!on.isEmpty() || !off.isEmpty()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + int id = boneData.getId(); + if (!on.isEmpty()) { + NetworkUtils.send(on, this.audienceGlowData(id, true, color)); + } + + if (!off.isEmpty()) { + NetworkUtils.send(off, this.audienceGlowData(id, false, color)); + } + } + } + } + } + } + } + + private ClientboundSetEntityDataPacket audienceGlowData(int entityId, boolean glowing, int color) { + ArrayList> entityData = new ArrayList<>(2); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(glowing ? 96 : 32))); + if (glowing) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + + return new ClientboundSetEntityDataPacket(entityId, entityData); + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + set.add((Packet)this.pivotCameraResize(pivot)); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(destroy)))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(hitboxDestroy)))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)(u -> this.displayData(u, null, boneData, false, transformOnly))); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + AnimationLODHandler.LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + RegistryFriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(RegistryFriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CODEC == null) { + Field field = ClientboundCustomPayloadPacket.class.getField("GAMEPLAY_STREAM_CODEC"); + field.setAccessible(true); + CUSTOM_PAYLOAD_CODEC = (StreamCodec)field.get(null); + } + + return (Packet)CUSTOM_PAYLOAD_CODEC.decode(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData( + BulkEntityDataEncoder encoder, + UUID uuid, + @Nullable AnimationLODHandler.LODTracker tracker, + DisplayBone.BoneData boneData, + boolean force, + boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? new ClientboundSetEntityDataPacket(pivot.getId(), this.cameraPivotData(pivot.getCameraHeight().get())) + : new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private List> cameraPivotData(float height) { + return List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(8, EntityDataSerializers.FLOAT, 0.0F), + new DataValue(9, EntityDataSerializers.FLOAT, height) + ); + } + + private ClientboundSetPassengersPacket pivotMount(DisplayRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(DisplayRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundSetEntityDataPacket pivotCameraResize(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() && pivot.getCameraHeight().isDirty() + ? new ClientboundSetEntityDataPacket(pivot.getId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, pivot.getCameraHeight().get()))) + : null; + } + + private ClientboundAddEntityPacket displaySpawn(DisplayRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData( + UUID uuid, @Nullable AnimationLODHandler.LODTracker tracker, DisplayBone.BoneData boneData, boolean force, boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + ArrayList> entityData = new ArrayList<>(13); + if (!force && update != 0) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : lodTick)), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + entityData.add(new DataValue(16, EntityDataSerializers.INT, val)); + } + }, force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + } + }, force); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + + private ClientboundSetEntityDataPacket displayVisibleData(DisplayBone.BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)))); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color))); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val))); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F))); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)))); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()))); + this.cleanupQueue.add(bone::clearDirty); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(DisplayRenderer.Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(DisplayRenderer.Hitbox hitbox) { + return !hitbox.isPivotVisible() ? null : new ClientboundSetEntityDataPacket(hitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket hitboxSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(4); + hitbox.getWidth().ifDirty(val -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, val)), spawn); + hitbox.getHeight().ifDirty(val -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getHitboxId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(2); + hitbox.getShadowRadius().ifDirty(val -> entityData.add(new DataValue(18, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getShadowId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(DisplayRenderer.Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(DisplayRenderer.Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + return new ClientboundSetPassengersPacket(EntityContainer.of(hitbox.getPivotId(), passengers)); + } + } +} diff --git a/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/vfx/VFXDisplayParser.java b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..759f311 --- /dev/null +++ b/nms/v1_21_R4/src/main/java/com/ticxo/modelengine/v1_21_R4/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,124 @@ +package com.ticxo.modelengine.v1_21_R4.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R4.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R4.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R4.network.utils.Packets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(new int[]{vfx.getPivotId(), vfx.getModelId()})); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXDisplayRenderer.VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetEntityDataPacket(vfx.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXDisplayRenderer.VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXDisplayRenderer.VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(9); + if (spawn) { + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)32)); + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, 4096.0F)); + entityData.add(new DataValue(24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal())); + } else if (vfx.isModelDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + vfx.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + vfx.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + vfx.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + vfx.clearModelDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(vfx.getModelId(), entityData); + } + } + + private Object teleport(VFXDisplayRenderer.VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetPassengersPacket(EntityContainer.of(vfx.getPivotId(), vfx.getModelId())); + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSFields.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSFields.java new file mode 100644 index 0000000..faeacbb --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSFields.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_21_R5; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionUtils.ReflectionEnum { + ENTITY_dimensions(Entity.class, "by", "dimensions"), + ENTITY_eyeHeight(Entity.class, "bz", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "cn", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "bB", "jumping"), + MOB_lookControl(Mob.class, "cd", "lookControl"), + MOB_moveControl(Mob.class, "ce", "moveControl"), + MOB_navigation(Mob.class, "cg", "navigation"), + MOB_goalSelector(Mob.class, "ch", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "cp", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "I", "clientIsFloating"), + SERVER_COMMON_PACKET_LISTENER_IMPL_connection(ServerCommonPacketListenerImpl.class, "e", "connection"), + MOVE_CONTROL_operation(MoveControl.class, "k", "operation"), + TRACKED_ENTITY_serverEntity(TrackedEntity.class, "b", "serverEntity"), + TRACKED_ENTITY_range(TrackedEntity.class, "d", "range"), + LEVEL_threadSafeRandom(Level.class, "f", "threadSafeRandom"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "a", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "b", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(final Class target, final String obfuscated, final String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSHandler_v1_21_R5.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSHandler_v1_21_R5.java new file mode 100644 index 0000000..c732d73 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSHandler_v1_21_R5.java @@ -0,0 +1,231 @@ +package com.ticxo.modelengine.v1_21_R5; + +import com.mojang.math.MatrixUtil; +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.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R5.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_21_R5.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R5.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_21_R5.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_21_R5.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_21_R5.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_21_R5.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_21_R5.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_21_R5.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.components.CustomModelDataComponent; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_21_R5 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + private boolean manualTranslucencyOrder; + private boolean forceCMD; + + public NMSHandler_v1_21_R5() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + public void updateConfig() { + this.manualTranslucencyOrder = ConfigProperty.MANUAL_TRANSLUCENCY_ORDER.getBoolean(); + this.forceCMD = ConfigProperty.FORCE_CMD.getBoolean(); + } + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + RegistryFriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, NetworkUtils.create(ClientboundSetPassengersPacket.class, byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public Set createStack(ItemModelData data, ItemModelData.Context context) { + if (this.forceCMD) { + return NMSHandler.super.createStack(data, context); + } else { + ItemStack item = new ItemStack(this.manualTranslucencyOrder && !data.isTranslucent() ? Material.GLASS : Material.BONE); + item.editMeta(itemMeta -> { + itemMeta.setItemModel(data.getSingleComposite().model()); + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(context.color())); + if (data.getVariant() != null) { + cmdComp.setStrings(List.of(data.getVariant())); + } + + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return Set.of(item); + } + } + + @Override + public boolean colorStack(ItemStack stack, Color color) { + stack.editMeta(itemMeta -> { + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(color)); + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return true; + } + + @Override + public void applyPlayerHeadItemModel(ItemStack stack) { + stack.editMeta(meta -> meta.setItemModel(this.getPlayerHeadModelKey())); + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(EntityContainer.of(mountId, passengerIds)); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSMethods.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSMethods.java new file mode 100644 index 0000000..bba222b --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/NMSMethods.java @@ -0,0 +1,49 @@ +package com.ticxo.modelengine.v1_21_R5; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.core.HolderLookup.Provider; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements ReflectionUtils.MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "a", "getInstrument", ItemStack.class, Provider.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityContainer.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityContainer.java new file mode 100644 index 0000000..b61308c --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityContainer.java @@ -0,0 +1,60 @@ +package com.ticxo.modelengine.v1_21_R5.entity; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.network.syncher.SynchedEntityData.Builder; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.ApiStatus.Internal; + +@Internal +public class EntityContainer extends Entity { + public static EntityContainer of(int id) { + return new EntityContainer(id); + } + + public static Entity of(int id, int... passengerIds) { + EntityContainer container = of(id); + container.setPassengers(Arrays.stream(passengerIds).mapToObj(EntityContainer::new).toList()); + return container; + } + + public static Entity of(int id, Collection passengerIds) { + EntityContainer container = of(id); + container.setPassengers(passengerIds.stream().map(EntityContainer::new).toList()); + return container; + } + + private EntityContainer(int id) { + super(EntityType.INTERACTION, MinecraftServer.getServer().overworld()); + this.setId(id); + this.setPosRaw(0.0, 0.0, 0.0); + this.setRot(0.0F, 0.0F); + this.setOnGround(false); + } + + protected void setPassengers(List passengers) { + this.passengers = ImmutableList.copyOf(passengers); + } + + protected void defineSynchedData(@NotNull Builder builder) { + } + + public boolean hurtServer(ServerLevel world, DamageSource source, float amount) { + return false; + } + + protected void readAdditionalSaveData(ValueInput valueInput) { + } + + protected void addAdditionalSaveData(ValueOutput valueOutput) { + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityHandlerImpl.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..82bb283 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityHandlerImpl.java @@ -0,0 +1,755 @@ +package com.ticxo.modelengine.v1_21_R5.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_21_R5.NMSFields; +import com.ticxo.modelengine.v1_21_R5.NMSMethods; +import com.ticxo.modelengine.v1_21_R5.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_21_R5.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_21_R5.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_21_R5.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_21_R5.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_21_R5.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_21_R5.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R5.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_21_R5.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R5.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.Packets; +import io.papermc.paper.adventure.PaperAdventure; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.kyori.adventure.text.Component; +import net.minecraft.core.Holder; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult.Fail; +import net.minecraft.world.InteractionResult.Pass; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.TryEmptyHandInteraction; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityAttachments; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemUseAnimation; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + float width = (float)hitbox.getMaxWidth(); + float height = (float)hitbox.getHeight(); + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions(width, height, (float)hitbox.getEyeHeight(), EntityAttachments.createDefault(width, height), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + if (EntityUtils.nms(entity) instanceof LivingEntity living) { + living.getAttributes().registerAttribute(Attributes.STEP_HEIGHT); + Objects.requireNonNull(living.getAttribute(Attributes.STEP_HEIGHT)).setBaseValue(height); + } + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityType.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y - nmsEntity.getVehicleAttachmentPoint(this.dummyArmorStand).y; + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + entity.getEntityId(), List.of(new DataValue(0, EntityDataSerializers.BYTE, data)) + ); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + switch (oldNav) { + case WallClimberNavigation wallClimberNavigation: + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + break; + case GroundPathNavigation groundPathNavigation: + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + break; + case FlyingPathNavigation flyingPathNavigation: + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + break; + case WaterBoundPathNavigation waterBoundPathNavigation: + newNav = new WaterBoundNavigationWrapper(mob); + break; + case AmphibiousPathNavigation amphibiousPathNavigation: + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + break; + default: + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var13) { + var13.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + ServerLevel level = ((CraftWorld)location.getWorld()).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity.level() instanceof ServerLevel worldserver) { + return nmsEntity.hurtServer(worldserver, damageSource, amount); + } + } + + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + + @Override + public EntityHandler.InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case Success success -> success.equals(net.minecraft.world.InteractionResult.SUCCESS_SERVER) + ? EntityHandler.InteractionResult.SUCCESS + : ( + success.equals(net.minecraft.world.InteractionResult.SUCCESS) + ? EntityHandler.InteractionResult.CONSUME_PARTIAL + : EntityHandler.InteractionResult.CONSUME + ); + case TryEmptyHandInteraction ignored -> EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED; + case Pass ignoredx -> EntityHandler.InteractionResult.PASS; + case Fail ignoredxx -> EntityHandler.InteractionResult.FAIL; + default -> throw new MatchException(null, null); + }; + } else { + return EntityHandler.InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket( + DynamicHitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA + ); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(DynamicHitbox.getHitboxId(), EntityUtils.DEFAULT_SLIME_DATA); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket( + EntityContainer.of(DynamicHitbox.getPivotId(), DynamicHitbox.getHitboxId()) + ); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0, 0.0F, 0.0F + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != ItemUseAnimation.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + player.getEntityId(), List.of(new DataValue(8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3))) + ); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call( + instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack, nmsPlayer.registryAccess() + ); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public Float getCameraEyeHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return nmsEntity.getDimensions(Pose.STANDING).eyeHeight(); + } + + @Override + public Float getCameraPivotHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + EntityDimensions dimensions = nmsEntity.getDimensions(nmsEntity.getPose()); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 attachment = ReflectionUtils.call(nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, dimensions, 1.0F); + return attachment == null ? null : (float)(dimensions.eyeHeight() - attachment.y); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public Set getCollidableExemptions(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity living ? living.collidableExemptions : null; + } + + @Override + public Component getCustomName(Entity entity) { + net.minecraft.network.chat.Component name = EntityUtils.nms(entity).getCustomName(); + return name == null ? null : PaperAdventure.asAdventure(name); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = level.getChunkSource().chunkMap.entityMap; + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = lvl.getChunkSource().chunkMap.entityMap; + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + EntityHandler.BoxRelToCam relX = EntityHandler.BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + EntityHandler.BoxRelToCam relY = EntityHandler.BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + EntityHandler.BoxRelToCam relZ = EntityHandler.BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == EntityHandler.BoxRelToCam.INSIDE && relY == EntityHandler.BoxRelToCam.INSIDE && relZ == EntityHandler.BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.DUST, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityMetadataID.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityMetadataID.java new file mode 100644 index 0000000..1b28b33 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityMetadataID.java @@ -0,0 +1,37 @@ +package com.ticxo.modelengine.v1_21_R5.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_POS_ROT_DURATION = 10; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityUtils.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityUtils.java new file mode 100644 index 0000000..bf29a24 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/EntityUtils.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.v1_21_R5.entity; + +import java.util.List; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.entity.CraftEntity; + +public class EntityUtils { + public static final List> DEFAULT_AREA_EFFECT_CLOUD_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(8, EntityDataSerializers.FLOAT, 0.0F) + ); + public static final List> DEFAULT_PIVOT_DISPLAY_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(10, EntityDataSerializers.INT, 1) + ); + public static final List> DEFAULT_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(16, EntityDataSerializers.INT, 2) + ); + public static final List> DEFAULT_BAT_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE) + ); + public static final List> DEFAULT_ARMOR_STAND_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(15, EntityDataSerializers.BYTE, (byte)16) + ); + + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/OcclusionClipContext.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/OcclusionClipContext.java new file mode 100644 index 0000000..b6c18e5 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v1_21_R5.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape() == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (!(tX <= 1.0) && !(tY <= 1.0) && !(tZ <= 1.0)) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/TrackedEntityImpl.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..9580422 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/TrackedEntityImpl.java @@ -0,0 +1,286 @@ +package com.ticxo.modelengine.v1_21_R5.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R5.NMSFields; +import com.ticxo.modelengine.v1_21_R5.NMSMethods; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } + + @Override + public boolean isViewerSetUnchanged() { + if ((!this.mayHaveForced || this.forcedPairing.isEmpty() && this.forcedRemove.isEmpty()) && this.playerPredicate == DEFAULT_PREDICATE) { + if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } else { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/BodyRotationControlWrapper.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..d6cd780 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_21_R5.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/LookControlWrapper.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..6fd9d6d --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/LookControlWrapper.java @@ -0,0 +1,152 @@ +package com.ticxo.modelengine.v1_21_R5.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import io.papermc.paper.entity.activation.ActivationRange; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + private MovementOverride movementOverride; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateDirection(this, this.modeledEntity); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/MoveControlWrapper.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..4e36345 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/controller/MoveControlWrapper.java @@ -0,0 +1,272 @@ +package com.ticxo.modelengine.v1_21_R5.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R5.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.Input; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + protected MovementOverride movementOverride; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateMovement(this, modeledEntity); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + if (entity instanceof Player player) { + Input playerInput = player.getCurrentInput(); + controller.setInput( + new MountController.MountInput( + playerInput.isForward(), + playerInput.isBackward(), + playerInput.isLeft(), + playerInput.isRight(), + playerInput.isJump(), + playerInput.isSneak(), + playerInput.isSprint() + ) + ); + } else { + controller.setInput(new MountController.MountInput()); + } + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/hitbox/HitboxEntityImpl.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..54d397c --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,271 @@ +package com.ticxo.modelengine.v1_21_R5.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_21_R5.NMSFields; +import com.ticxo.modelengine.v1_21_R5.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + @NotNull + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public boolean isInvisible() { + return true; + } + + public void push(@NotNull Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox(Vec3 position) { + if (this.subHitbox == null) { + return super.makeBoundingBox(position); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(@NotNull Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurtServer(@NotNull ServerLevel world, @NotNull DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurtServer(world, source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + BaseEntity baseEntity = this.bone.getActiveModel().getModeledEntity().getBase(); + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return baseEntity.hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, @NotNull InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, entity, new Vector(0, 0, 0), hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact(this, player.getBukkitEntity(), hand == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND); + + return (InteractionResult)(switch (result) { + case SUCCESS -> InteractionResult.SUCCESS_SERVER; + case SUCCESS_NO_ITEM_USED -> InteractionResult.TRY_WITH_EMPTY_HAND; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.SUCCESS; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }); + } + } + + public boolean shouldBeSaved() { + return false; + } + + @NotNull + public CraftEntity getBukkitEntity() { + CraftEntity bukkitEntity = this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + CraftEntity var5 = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(var5); + return var5; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(@NotNull RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/hitbox/OBB.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/hitbox/OBB.java new file mode 100644 index 0000000..0128163 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R5.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..2fddeb7 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R5.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..e9b06dc --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R5.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/GroundNavigationWrapper.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..3b16f49 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R5.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..e807874 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R5.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..2952e29 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_21_R5.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/ModelEngineChannelHandler.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..7a83794 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/ModelEngineChannelHandler.java @@ -0,0 +1,457 @@ +package com.ticxo.modelengine.v1_21_R5.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R5.NMSFields; +import com.ticxo.modelengine.v1_21_R5.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R5.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntList; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundEntityPositionSyncPacket.class, this::handlePositionSync) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove) + .register(ServerboundClientTickEndPacket.class, this::handleClientTickEnd); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet rawPacket && asClientPacket(rawPacket) instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + Collection> post = this.writeInterceptors.acceptPost(result); + if (!post.isEmpty()) { + list.addAll(post); + } + } + } + + if (!list.isEmpty()) { + Packet var12 = new ClientboundBundlePacket(list); + super.write(ctx, var12, promise); + } + } else { + Packet var13 = this.writeInterceptors.accept(packet); + if (var13 == null) { + return; + } + + Collection> post = this.writeInterceptors.acceptPost(var13); + if (post.isEmpty()) { + super.write(ctx, var13, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var13); + list.addAll(post); + Packet var14 = new ClientboundBundlePacket(list); + super.write(ctx, var14, promise); + } + } + } catch (Throwable var11) { + var11.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List> handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List> handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + List> list = null; + Optional maybeMount = model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT); + if (maybeMount.isPresent() && maybeMount.get() instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + MountRenderer.Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + if (mount == null) { + return null; + } + + CollectionDataTracker ids = mount.getPassengers(); + list = new ArrayList<>(); + list.add(new ClientboundSetPassengersPacket(EntityContainer.of(mount.getMountId(), ids))); + } + } + + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + IntList ids = packet.getEntityIds(); + + for (int i = 0; i < ids.size(); i++) { + this.markViewersDirty(ids.getInt(i)); + } + + int[] set = packet.getEntityIds().intStream().filter(id -> ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE).toArray(); + return set.length == packet.getEntityIds().size() ? packet : new ClientboundRemoveEntitiesPacket(IntArrayList.wrap(set)); + } + + private > T handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readClientbound(packet); + + Packet var4; + try { + int id = buf.readVarInt(); + var4 = ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } finally { + buf.release(); + } + + return (T)var4; + } + + private > T handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundEntityPositionSyncPacket handlePositionSync(ClientboundEntityPositionSyncPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + int id = packet.entityId(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + return !changed ? packet : new ClientboundSetPassengersPacket(EntityContainer.of(packet.getVehicle(), new IntArrayList(merged))); + } + } + } + + private Packet handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readServerbound(packet); + + int entityId; + int action; + try { + entityId = buf.readVarInt(); + action = buf.readVarInt(); + } finally { + buf.release(); + } + + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), action, packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, action, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, action, packet) : packet); + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountController.MountInput input = controller.getInput(); + if (input == null) { + controller.setInput( + new MountController.MountInput( + inputPacket.input().forward(), + inputPacket.input().backward(), + inputPacket.input().left(), + inputPacket.input().right(), + inputPacket.input().jump(), + inputPacket.input().shift(), + inputPacket.input().sprint() + ) + ); + } else { + input.setForward(inputPacket.input().forward()); + input.setBackward(inputPacket.input().backward()); + input.setLeft(inputPacket.input().left()); + input.setRight(inputPacket.input().right()); + input.setJump(inputPacket.input().jump()); + input.setSneak(inputPacket.input().shift()); + input.setSprint(inputPacket.input().sprint()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + if (!ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + private ServerboundClientTickEndPacket handleClientTickEnd(ServerboundClientTickEndPacket packet) { + if (ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + @SuppressWarnings("unchecked") + private static Packet asClientPacket(Object packet) { + return (Packet)packet; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/NetworkHandlerImpl.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..99068a3 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/NetworkHandlerImpl.java @@ -0,0 +1,141 @@ +package com.ticxo.modelengine.v1_21_R5.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R5.NMSFields; +import com.ticxo.modelengine.v1_21_R5.network.utils.Bundler; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection> collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/patch/PatchedServerGamePacketListener.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..f779bbb --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,439 @@ +package com.ticxo.modelengine.v1_21_R5.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R5.NMSMethods; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.SwingSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(final ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().level()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.level(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + ModelBone hitBone = null; + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel == null) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(interactPacket.getRelayedId()); + if (hitbox != null) { + hitBone = hitbox.getBone(); + activeModel = hitBone.getActiveModel(); + } + } + + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + final ActiveModel finalActiveModel = activeModel; + final ModelBone finalHitBone = hitBone; + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + null, + finalHitBone + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + position, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + position, + finalHitBone + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.ATTACK, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, null); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, pos); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent( + craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND, null + ); + } + } + ); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= player.entityInteractionRange() * player.entityInteractionRange())) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelectedItem().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem)) { + if (player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + ServerEntity serverEntity = entity.moonrise$getTrackedEntity().serverEntity; + List> list = new ArrayList<>(); + serverEntity.sendPairingData(player, list::add); + player.connection.send(new ClientboundBundlePacket(list)); + } + + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem) { + List> data = entity.getEntityData().packAll(); + if (data != null && player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + player.connection.send(new ClientboundSetEntityDataPacket(entity.getId(), data)); + } + + if (entity instanceof Allay allay) { + List> equipment = Arrays.stream(EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.getItemBySlot(slot))) + .collect(Collectors.toList()); + connection.send(new ClientboundSetEquipmentPacket(entity.getId(), equipment)); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.level()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.level(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level().clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.isSameItemSameComponents(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand, + movingobjectpositionblock.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, itemstack, enumhand); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.resyncUsingItem(player); + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent( + CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacketWrapper packet, InteractionHand hand, @Nullable Vec3 vector + ) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.isAttack(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND, + vector != null ? new Vector(vector.x, vector.y, vector.z) : null + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..753fd5b --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,75 @@ +package com.ticxo.modelengine.v1_21_R5.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper implements Packet { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + private final boolean isAttack; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, int action, ServerboundInteractPacket original) { + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + this.isAttack = action == 1; + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_INTERACT; + } + + public int getEntityId() { + return this.originalId; + } + + public boolean isAttack() { + return this.isAttack; + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/BulkEntityDataEncoder.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..e037d94 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R5.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/Bundler.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/Bundler.java new file mode 100644 index 0000000..483d6c6 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_21_R5.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.getLast(); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection> packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.getLast(); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet packet : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/NetworkUtils.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/NetworkUtils.java new file mode 100644 index 0000000..3949f35 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/NetworkUtils.java @@ -0,0 +1,354 @@ +package com.ticxo.modelengine.v1_21_R5.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R5.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R5.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.GameProtocols.Context; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static final ProtocolInfo CLIENTBOUND_CODEC = GameProtocols.CLIENTBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + public static final ProtocolInfo SERVERBOUND_CODEC = GameProtocols.SERVERBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess()), (Context)() -> false); + private static final Map, Constructor> PACKET_CONSTRUCTOR = new HashMap<>(); + + public static RegistryFriendlyByteBuf createByteBuf() { + return new RegistryFriendlyByteBuf(Unpooled.buffer(), MinecraftServer.getServer().registryAccess()); + } + + public static RegistryFriendlyByteBuf createByteBuf(Consumer consumer) { + RegistryFriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static > T create(Class clazz, RegistryFriendlyByteBuf buf) { + Constructor constructor = PACKET_CONSTRUCTOR.computeIfAbsent(clazz, aClass -> { + try { + Constructor c = aClass.getDeclaredConstructor(RegistryFriendlyByteBuf.class); + c.setAccessible(true); + return c; + } catch (NoSuchMethodException var4x) { + try { + Constructor cx = aClass.getDeclaredConstructor(FriendlyByteBuf.class); + cx.setAccessible(true); + return cx; + } catch (NoSuchMethodException var3) { + throw new RuntimeException(var3); + } + } + }); + + try { + return (T)constructor.newInstance(buf); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException var4) { + throw new RuntimeException(var4); + } + } + + public static FriendlyByteBuf readServerbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + SERVERBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static FriendlyByteBuf readClientbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + CLIENTBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createCameraPivotSpawn(int id, UUID uuid, Vector3f pos, float height) { + ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket( + id, uuid, pos.x, pos.y - height, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createCameraPivotTeleport(int id, Vector3f pos, float height) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - height, pos.z); + ClientboundEntityPositionSyncPacket packet = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createDisplayPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - 0.375, pos.z); + ClientboundEntityPositionSyncPacket tpHigher = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + container = EntityContainer.of(id); + container.setId(id); + container.setPosRaw(pos.x, pos.y - 0.5, pos.z); + ClientboundEntityPositionSyncPacket tpLower = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Object createCameraPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos, float height) { + if (codec == null) { + return createCameraPivotTeleport(id, pos, height); + } else { + return switch (codec.update(pos.x, pos.y - height, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createCameraPivotTeleport(id, pos, height); + }; + } + } + + public static Packets.PacketSupplier createDisplayPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y, pos.z); + return playerUUID -> new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + public static Packets.PacketSupplier lodWrapper( + ModeledEntity modeledEntity, BiFunction> packetFunction + ) { + return uuid -> { + AnimationLODHandler.LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/PacketInterceptor.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..0acc011 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/PacketInterceptor.java @@ -0,0 +1,84 @@ +package com.ticxo.modelengine.v1_21_R5.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor

    { + private final Map>, PacketInterceptor

    .Modifier>> registry = Maps.newConcurrentMap(); + private final Map>, PacketInterceptor

    .Listener>> postRegistry = Maps.newConcurrentMap(); + + public > PacketInterceptor

    register(Class clazz, Function> function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public > PacketInterceptor

    registerPost(Class clazz, Function>> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor

    .Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection> acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor

    .Listener listener = this.postRegistry.get(original.getClass()); + return (Collection>)(listener != null ? listener.listen(original) : List.of()); + } + } + + class Listener> { + private final Class clazz; + private final Function>> function; + + public Collection> listen(Packet original) { + try { + Collection> collection = this.function.apply(this.clazz.cast(original)); + return (Collection>)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(final Class clazz, final Function>> function) { + this.clazz = clazz; + this.function = function; + } + } + + class Modifier> { + private final Class clazz; + private final Function> function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(final Class clazz, final Function> function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/Packets.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/Packets.java new file mode 100644 index 0000000..1e22991 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_21_R5.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/HeldItemParser.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..401eabe --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/HeldItemParser.java @@ -0,0 +1,186 @@ +package com.ticxo.modelengine.v1_21_R5.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R5.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Quaternionf; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapToInt(HeldItemRenderer.Item::getId)) + )) + ); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Map items = renderer.getRendered(); + IntArrayList entityIds = IntArrayList.toList(items.values().stream().mapToInt(HeldItemRenderer.Item::getId)); + entityIds.add(renderer.getId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + return new ClientboundSetEntityDataPacket(renderer.getId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, HeldItemRenderer.Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(HeldItemRenderer.Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(11); + if (spawn) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, this.viewRange)); + } else if (renderer.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + renderer.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), spawn); + renderer.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), spawn); + renderer.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getRotation() + .ifDirty( + quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf.rotateY((float) Math.PI, new Quaternionf()))), + spawn + ); + renderer.getModel() + .ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + renderer.getDisplay() + .ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getId(), entityData); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location loc = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(loc.getX(), loc.getY(), loc.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + EntityContainer container = EntityContainer.of(renderer.getId()); + container.setPosRaw(loc.getX(), loc.getY(), loc.getZ()); + return new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getId(), renderer.getPassengers())); + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/LeashParser.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/LeashParser.java new file mode 100644 index 0000000..0ec65a7 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/LeashParser.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.v1_21_R5.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Map leashes = renderer.getRendered(); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(IntArrayList.toList(leashes.values().stream().mapMultiToInt((leash, intConsumer) -> { + intConsumer.accept(leash.getLeashId()); + intConsumer.accept(leash.getPivotId()); + })))); + } + } + + private Packets.PacketSupplier pivotSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + + private ClientboundAddEntityPacket leashSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y - 0.45, pos.z - 0.2, 0.0F, 0.0F, EntityType.BAT, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetEntityDataPacket leashData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getLeashId(), EntityUtils.DEFAULT_BAT_DATA); + } + + private ClientboundSetPassengersPacket mount(LeashRenderer.Leash renderer) { + ArrayList passengers = new ArrayList<>(1); + passengers.add(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), passengers)); + } + + private Object move(LeashRenderer.Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + } + + private ClientboundSetEntityLinkPacket link(LeashRenderer.Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(EntityContainer.of(renderer.getLeashId()), EntityContainer.of(renderer.getConnected().get())); + } + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/MountParser.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/MountParser.java new file mode 100644 index 0000000..a43aa44 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/MountParser.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.v1_21_R5.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R5.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getMountId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Collection mounts = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(mounts.size() * 2); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getMountId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_PIVOT_DISPLAY_DATA); + } + + private ClientboundAddEntityPacket mountSpawn(MountRenderer.Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getMountId())); + } + + private ClientboundSetPassengersPacket mount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getMountId(), renderer.getPassengers())); + } + + private Packets.PacketSupplier pivotMove(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(MountRenderer.Mount renderer) { + return new Rot(renderer.getMountId(), renderer.getYaw().get(), (byte)0, false); + } + + private ClientboundSetEntityDataPacket mountHealth(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, renderer.getHealth().get()))); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(MountRenderer.Mount renderer) { + AttributeInstance attributeInstance = new AttributeInstance(Attributes.MAX_HEALTH, onDirty -> {}); + attributeInstance.setBaseValue(renderer.getMaxHealth().get().floatValue()); + return new ClientboundUpdateAttributesPacket(renderer.getMountId(), Lists.newArrayList(new AttributeInstance[]{attributeInstance})); + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/NameTagParser.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..ab78989 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/NameTagParser.java @@ -0,0 +1,184 @@ +package com.ticxo.modelengine.v1_21_R5.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTagRenderer.NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTagRenderer.NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Collection nameTags = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(nameTags.size() * 2); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + return !spawn ? null : new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTagRenderer.NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(7); + renderer.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + renderer.getTranslate().ifDirty(flag -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getScale().ifDirty(flag -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getTextOpacity().ifDirty(flag -> entityData.add(new DataValue(26, EntityDataSerializers.BYTE, flag)), spawn); + renderer.getBackgroundColor().ifDirty(flag -> entityData.add(new DataValue(25, EntityDataSerializers.INT, flag)), spawn); + renderer.getStyle().ifDirty(flags -> entityData.add(new DataValue(27, EntityDataSerializers.BYTE, flags)), spawn); + renderer.getLineWidth().ifDirty(flag -> entityData.add(new DataValue(24, EntityDataSerializers.INT, flag)), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new MatchException(null, null); + }; + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, value)); + }, spawn); + renderer.getJsonString() + .ifDirty( + jsonString -> { + if (jsonString == null) { + entityData.add(new DataValue(23, EntityDataSerializers.COMPONENT, Component.empty())); + } else { + entityData.add( + new DataValue(23, EntityDataSerializers.COMPONENT, Optional.ofNullable(CraftChatMessage.fromJSON(jsonString)).orElse(Component.empty())) + ); + } + }, + spawn + ); + renderer.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getTagId(), entityData); + } + } + + private Object pivotMove(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTagRenderer.NameTag renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getTagId())); + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/SegmentParser.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..d3b9435 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/SegmentParser.java @@ -0,0 +1,205 @@ +package com.ticxo.modelengine.v1_21_R5.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R5.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (SegmentRenderer.Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + IntArrayList destroy = new IntArrayList(); + + for (SegmentRenderer.Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(destroy))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(SegmentRenderer.Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SegmentRenderer.Pivot pivot) { + return new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(SegmentRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(SegmentRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(SegmentRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + ArrayList> entityData = new ArrayList<>(13); + if (force) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } else if (bone.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : 1)), force); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), force); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/SubHitboxParser.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..56eeba2 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/behavior/SubHitboxParser.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R5.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitboxRenderer.SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Collection subHitboxes = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(subHitboxes.size() * 2); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private Object pivotMove(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getHitboxId())); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitboxRenderer.SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitboxRenderer.SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(4); + renderer.getWidth().ifDirty(width -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, width)), spawn); + renderer.getHeight().ifDirty(height -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, height)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getHitboxId(), entityData); + } + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/model/DisplayParser.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/model/DisplayParser.java new file mode 100644 index 0000000..6635e74 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/model/DisplayParser.java @@ -0,0 +1,789 @@ +package com.ticxo.modelengine.v1_21_R5.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R5.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static StreamCodec CUSTOM_PAYLOAD_CODEC; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + if (renderer.hasGlowAudience()) { + this.updateAudienceGlow(renderer, data.getTracking().keySet(), data.getStartTracking(), this.noCullForcePlayers); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + private void updateAudienceGlow(DisplayRenderer renderer, Set current, Set startTracking, Set forceUpdates) { + for (DisplayBone bone : renderer.getRendered().values()) { + Set audience = bone.getGlowAudience().get(); + if (audience != null) { + boolean changed = bone.isAudienceGlowDirty(); + if (changed || !startTracking.isEmpty() || !forceUpdates.isEmpty()) { + boolean glowing = bone.getAudienceGlowing().get(); + int color = bone.getAudienceGlowColor().get(); + Set on = new HashSet<>(); + Set off = new HashSet<>(); + if (changed) { + for (UUID uuid : current) { + if (glowing && audience.contains(uuid)) { + on.add(uuid); + } else { + off.add(uuid); + } + } + + bone.clearAudienceGlowDirty(); + } else if (glowing) { + for (UUID uuidx : startTracking) { + if (audience.contains(uuidx)) { + on.add(uuidx); + } + } + + for (UUID uuidxx : forceUpdates) { + if (audience.contains(uuidxx)) { + on.add(uuidxx); + } + } + } + + if (!on.isEmpty() || !off.isEmpty()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + int id = boneData.getId(); + if (!on.isEmpty()) { + NetworkUtils.send(on, this.audienceGlowData(id, true, color)); + } + + if (!off.isEmpty()) { + NetworkUtils.send(off, this.audienceGlowData(id, false, color)); + } + } + } + } + } + } + } + + private ClientboundSetEntityDataPacket audienceGlowData(int entityId, boolean glowing, int color) { + ArrayList> entityData = new ArrayList<>(2); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(glowing ? 96 : 32))); + if (glowing) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + + return new ClientboundSetEntityDataPacket(entityId, entityData); + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + set.add((Packet)this.pivotCameraResize(pivot)); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(destroy)))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(hitboxDestroy)))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)(u -> this.displayData(u, null, boneData, false, transformOnly))); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + AnimationLODHandler.LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + RegistryFriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(RegistryFriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CODEC == null) { + Field field = ClientboundCustomPayloadPacket.class.getField("GAMEPLAY_STREAM_CODEC"); + field.setAccessible(true); + CUSTOM_PAYLOAD_CODEC = (StreamCodec)field.get(null); + } + + return (Packet)CUSTOM_PAYLOAD_CODEC.decode(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData( + BulkEntityDataEncoder encoder, + UUID uuid, + @Nullable AnimationLODHandler.LODTracker tracker, + DisplayBone.BoneData boneData, + boolean force, + boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? new ClientboundSetEntityDataPacket(pivot.getId(), this.cameraPivotData(pivot.getCameraHeight().get())) + : new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private List> cameraPivotData(float height) { + return List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(8, EntityDataSerializers.FLOAT, 0.0F), + new DataValue(9, EntityDataSerializers.FLOAT, height) + ); + } + + private ClientboundSetPassengersPacket pivotMount(DisplayRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(DisplayRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundSetEntityDataPacket pivotCameraResize(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() && pivot.getCameraHeight().isDirty() + ? new ClientboundSetEntityDataPacket(pivot.getId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, pivot.getCameraHeight().get()))) + : null; + } + + private ClientboundAddEntityPacket displaySpawn(DisplayRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData( + UUID uuid, @Nullable AnimationLODHandler.LODTracker tracker, DisplayBone.BoneData boneData, boolean force, boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + ArrayList> entityData = new ArrayList<>(13); + if (!force && update != 0) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : lodTick)), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + entityData.add(new DataValue(16, EntityDataSerializers.INT, val)); + } + }, force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + } + }, force); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + + private ClientboundSetEntityDataPacket displayVisibleData(DisplayBone.BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)))); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color))); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val))); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F))); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)))); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()))); + this.cleanupQueue.add(bone::clearDirty); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(DisplayRenderer.Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(DisplayRenderer.Hitbox hitbox) { + return !hitbox.isPivotVisible() ? null : new ClientboundSetEntityDataPacket(hitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket hitboxSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(4); + hitbox.getWidth().ifDirty(val -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, val)), spawn); + hitbox.getHeight().ifDirty(val -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getHitboxId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(2); + hitbox.getShadowRadius().ifDirty(val -> entityData.add(new DataValue(18, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getShadowId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(DisplayRenderer.Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(DisplayRenderer.Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + return new ClientboundSetPassengersPacket(EntityContainer.of(hitbox.getPivotId(), passengers)); + } + } +} diff --git a/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/vfx/VFXDisplayParser.java b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..f05de28 --- /dev/null +++ b/nms/v1_21_R5/src/main/java/com/ticxo/modelengine/v1_21_R5/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,124 @@ +package com.ticxo.modelengine.v1_21_R5.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R5.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R5.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R5.network.utils.Packets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(new int[]{vfx.getPivotId(), vfx.getModelId()})); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXDisplayRenderer.VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetEntityDataPacket(vfx.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXDisplayRenderer.VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXDisplayRenderer.VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(9); + if (spawn) { + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)32)); + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, 4096.0F)); + entityData.add(new DataValue(24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal())); + } else if (vfx.isModelDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + vfx.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + vfx.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + vfx.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + vfx.clearModelDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(vfx.getModelId(), entityData); + } + } + + private Object teleport(VFXDisplayRenderer.VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetPassengersPacket(EntityContainer.of(vfx.getPivotId(), vfx.getModelId())); + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSFields.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSFields.java new file mode 100644 index 0000000..05b792f --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSFields.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_21_R6; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionUtils.ReflectionEnum { + ENTITY_dimensions(Entity.class, "bz", "dimensions"), + ENTITY_eyeHeight(Entity.class, "bA", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "cu", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "bL", "jumping"), + MOB_lookControl(Mob.class, "cm", "lookControl"), + MOB_moveControl(Mob.class, "cn", "moveControl"), + MOB_navigation(Mob.class, "cp", "navigation"), + MOB_goalSelector(Mob.class, "cq", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "cy", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "I", "clientIsFloating"), + SERVER_COMMON_PACKET_LISTENER_IMPL_connection(ServerCommonPacketListenerImpl.class, "e", "connection"), + MOVE_CONTROL_operation(MoveControl.class, "k", "operation"), + TRACKED_ENTITY_serverEntity(TrackedEntity.class, "b", "serverEntity"), + TRACKED_ENTITY_range(TrackedEntity.class, "d", "range"), + LEVEL_threadSafeRandom(Level.class, "C", "threadSafeRandom"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "a", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "b", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(final Class target, final String obfuscated, final String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSHandler_v1_21_R6.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSHandler_v1_21_R6.java new file mode 100644 index 0000000..b30e852 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSHandler_v1_21_R6.java @@ -0,0 +1,231 @@ +package com.ticxo.modelengine.v1_21_R6; + +import com.mojang.math.MatrixUtil; +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.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R6.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_21_R6.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R6.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_21_R6.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_21_R6.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_21_R6.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_21_R6.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_21_R6.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_21_R6.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.components.CustomModelDataComponent; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_21_R6 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + private boolean manualTranslucencyOrder; + private boolean forceCMD; + + public NMSHandler_v1_21_R6() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + public void updateConfig() { + this.manualTranslucencyOrder = ConfigProperty.MANUAL_TRANSLUCENCY_ORDER.getBoolean(); + this.forceCMD = ConfigProperty.FORCE_CMD.getBoolean(); + } + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + RegistryFriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, NetworkUtils.create(ClientboundSetPassengersPacket.class, byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public Set createStack(ItemModelData data, ItemModelData.Context context) { + if (this.forceCMD) { + return NMSHandler.super.createStack(data, context); + } else { + ItemStack item = new ItemStack(this.manualTranslucencyOrder && !data.isTranslucent() ? Material.GLASS : Material.BONE); + item.editMeta(itemMeta -> { + itemMeta.setItemModel(data.getSingleComposite().model()); + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(context.color())); + if (data.getVariant() != null) { + cmdComp.setStrings(List.of(data.getVariant())); + } + + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return Set.of(item); + } + } + + @Override + public boolean colorStack(ItemStack stack, Color color) { + stack.editMeta(itemMeta -> { + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(color)); + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return true; + } + + @Override + public void applyPlayerHeadItemModel(ItemStack stack) { + stack.editMeta(meta -> meta.setItemModel(this.getPlayerHeadModelKey())); + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(EntityContainer.of(mountId, passengerIds)); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSMethods.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSMethods.java new file mode 100644 index 0000000..6cc5076 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/NMSMethods.java @@ -0,0 +1,49 @@ +package com.ticxo.modelengine.v1_21_R6; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.core.HolderLookup.Provider; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements ReflectionUtils.MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "a", "getInstrument", ItemStack.class, Provider.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityContainer.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityContainer.java new file mode 100644 index 0000000..3c8e698 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityContainer.java @@ -0,0 +1,60 @@ +package com.ticxo.modelengine.v1_21_R6.entity; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.network.syncher.SynchedEntityData.Builder; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.ApiStatus.Internal; + +@Internal +public class EntityContainer extends Entity { + public static EntityContainer of(int id) { + return new EntityContainer(id); + } + + public static Entity of(int id, int... passengerIds) { + EntityContainer container = of(id); + container.setPassengers(Arrays.stream(passengerIds).mapToObj(EntityContainer::new).toList()); + return container; + } + + public static Entity of(int id, Collection passengerIds) { + EntityContainer container = of(id); + container.setPassengers(passengerIds.stream().map(EntityContainer::new).toList()); + return container; + } + + private EntityContainer(int id) { + super(EntityType.INTERACTION, MinecraftServer.getServer().overworld()); + this.setId(id); + this.setPosRaw(0.0, 0.0, 0.0); + this.setRot(0.0F, 0.0F); + this.setOnGround(false); + } + + protected void setPassengers(List passengers) { + this.passengers = ImmutableList.copyOf(passengers); + } + + protected void defineSynchedData(@NotNull Builder builder) { + } + + public boolean hurtServer(ServerLevel world, DamageSource source, float amount) { + return false; + } + + protected void readAdditionalSaveData(ValueInput valueInput) { + } + + protected void addAdditionalSaveData(ValueOutput valueOutput) { + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityHandlerImpl.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..ccaf2f1 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityHandlerImpl.java @@ -0,0 +1,755 @@ +package com.ticxo.modelengine.v1_21_R6.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_21_R6.NMSFields; +import com.ticxo.modelengine.v1_21_R6.NMSMethods; +import com.ticxo.modelengine.v1_21_R6.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_21_R6.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_21_R6.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_21_R6.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_21_R6.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_21_R6.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_21_R6.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R6.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_21_R6.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R6.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.Packets; +import io.papermc.paper.adventure.PaperAdventure; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.kyori.adventure.text.Component; +import net.minecraft.core.Holder; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult.Fail; +import net.minecraft.world.InteractionResult.Pass; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.TryEmptyHandInteraction; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityAttachments; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemUseAnimation; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + float width = (float)hitbox.getMaxWidth(); + float height = (float)hitbox.getHeight(); + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions(width, height, (float)hitbox.getEyeHeight(), EntityAttachments.createDefault(width, height), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + if (EntityUtils.nms(entity) instanceof LivingEntity living) { + living.getAttributes().registerAttribute(Attributes.STEP_HEIGHT); + Objects.requireNonNull(living.getAttribute(Attributes.STEP_HEIGHT)).setBaseValue(height); + } + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityType.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y - nmsEntity.getVehicleAttachmentPoint(this.dummyArmorStand).y; + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + entity.getEntityId(), List.of(new DataValue(0, EntityDataSerializers.BYTE, data)) + ); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + switch (oldNav) { + case WallClimberNavigation wallClimberNavigation: + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + break; + case GroundPathNavigation groundPathNavigation: + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + break; + case FlyingPathNavigation flyingPathNavigation: + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + break; + case WaterBoundPathNavigation waterBoundPathNavigation: + newNav = new WaterBoundNavigationWrapper(mob); + break; + case AmphibiousPathNavigation amphibiousPathNavigation: + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + break; + default: + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var13) { + var13.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + ServerLevel level = ((CraftWorld)location.getWorld()).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity.level() instanceof ServerLevel worldserver) { + return nmsEntity.hurtServer(worldserver, damageSource, amount); + } + } + + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + + @Override + public EntityHandler.InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case Success success -> success.equals(net.minecraft.world.InteractionResult.SUCCESS_SERVER) + ? EntityHandler.InteractionResult.SUCCESS + : ( + success.equals(net.minecraft.world.InteractionResult.SUCCESS) + ? EntityHandler.InteractionResult.CONSUME_PARTIAL + : EntityHandler.InteractionResult.CONSUME + ); + case TryEmptyHandInteraction ignored -> EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED; + case Pass ignoredx -> EntityHandler.InteractionResult.PASS; + case Fail ignoredxx -> EntityHandler.InteractionResult.FAIL; + default -> throw new MatchException(null, null); + }; + } else { + return EntityHandler.InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket( + DynamicHitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA + ); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(DynamicHitbox.getHitboxId(), EntityUtils.DEFAULT_SLIME_DATA); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket( + EntityContainer.of(DynamicHitbox.getPivotId(), DynamicHitbox.getHitboxId()) + ); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0, 0.0F, 0.0F + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != ItemUseAnimation.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + player.getEntityId(), List.of(new DataValue(8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3))) + ); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call( + instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack, nmsPlayer.registryAccess() + ); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public Float getCameraEyeHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return nmsEntity.getDimensions(Pose.STANDING).eyeHeight(); + } + + @Override + public Float getCameraPivotHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + EntityDimensions dimensions = nmsEntity.getDimensions(nmsEntity.getPose()); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 attachment = ReflectionUtils.call(nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, dimensions, 1.0F); + return attachment == null ? null : (float)(dimensions.eyeHeight() - attachment.y); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public Set getCollidableExemptions(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity living ? living.collidableExemptions : null; + } + + @Override + public Component getCustomName(Entity entity) { + net.minecraft.network.chat.Component name = EntityUtils.nms(entity).getCustomName(); + return name == null ? null : PaperAdventure.asAdventure(name); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = level.getChunkSource().chunkMap.entityMap; + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = lvl.getChunkSource().chunkMap.entityMap; + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + EntityHandler.BoxRelToCam relX = EntityHandler.BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + EntityHandler.BoxRelToCam relY = EntityHandler.BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + EntityHandler.BoxRelToCam relZ = EntityHandler.BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == EntityHandler.BoxRelToCam.INSIDE && relY == EntityHandler.BoxRelToCam.INSIDE && relZ == EntityHandler.BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.DUST, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityMetadataID.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityMetadataID.java new file mode 100644 index 0000000..f81647c --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityMetadataID.java @@ -0,0 +1,37 @@ +package com.ticxo.modelengine.v1_21_R6.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_POS_ROT_DURATION = 10; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityUtils.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityUtils.java new file mode 100644 index 0000000..54e3ee7 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/EntityUtils.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.v1_21_R6.entity; + +import java.util.List; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.entity.CraftEntity; + +public class EntityUtils { + public static final List> DEFAULT_AREA_EFFECT_CLOUD_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(8, EntityDataSerializers.FLOAT, 0.0F) + ); + public static final List> DEFAULT_PIVOT_DISPLAY_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(10, EntityDataSerializers.INT, 1) + ); + public static final List> DEFAULT_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(16, EntityDataSerializers.INT, 2) + ); + public static final List> DEFAULT_BAT_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE) + ); + public static final List> DEFAULT_ARMOR_STAND_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(15, EntityDataSerializers.BYTE, (byte)16) + ); + + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/OcclusionClipContext.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/OcclusionClipContext.java new file mode 100644 index 0000000..7f333e6 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v1_21_R6.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape() == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (!(tX <= 1.0) && !(tY <= 1.0) && !(tZ <= 1.0)) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/TrackedEntityImpl.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..95876c1 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/TrackedEntityImpl.java @@ -0,0 +1,286 @@ +package com.ticxo.modelengine.v1_21_R6.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R6.NMSFields; +import com.ticxo.modelengine.v1_21_R6.NMSMethods; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player player = connection.getPlayer().getBukkitEntity(); + if (player != null + && predicate.test(player) + && this.playerPredicate.test(player) + && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } + + @Override + public boolean isViewerSetUnchanged() { + if ((!this.mayHaveForced || this.forcedPairing.isEmpty() && this.forcedRemove.isEmpty()) && this.playerPredicate == DEFAULT_PREDICATE) { + if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } else { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/BodyRotationControlWrapper.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..ebaf78b --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_21_R6.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/LookControlWrapper.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..8bf4a1f --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/LookControlWrapper.java @@ -0,0 +1,152 @@ +package com.ticxo.modelengine.v1_21_R6.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import io.papermc.paper.entity.activation.ActivationRange; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + private MovementOverride movementOverride; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateDirection(this, this.modeledEntity); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/MoveControlWrapper.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..45fb0dd --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/controller/MoveControlWrapper.java @@ -0,0 +1,272 @@ +package com.ticxo.modelengine.v1_21_R6.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R6.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.Input; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + protected MovementOverride movementOverride; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateMovement(this, modeledEntity); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + if (entity instanceof Player player) { + Input playerInput = player.getCurrentInput(); + controller.setInput( + new MountController.MountInput( + playerInput.isForward(), + playerInput.isBackward(), + playerInput.isLeft(), + playerInput.isRight(), + playerInput.isJump(), + playerInput.isSneak(), + playerInput.isSprint() + ) + ); + } else { + controller.setInput(new MountController.MountInput()); + } + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/hitbox/HitboxEntityImpl.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..56b628b --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,271 @@ +package com.ticxo.modelengine.v1_21_R6.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_21_R6.NMSFields; +import com.ticxo.modelengine.v1_21_R6.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + @NotNull + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public boolean isInvisible() { + return true; + } + + public void push(@NotNull Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox(Vec3 position) { + if (this.subHitbox == null) { + return super.makeBoundingBox(position); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(@NotNull Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurtServer(@NotNull ServerLevel world, @NotNull DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurtServer(world, source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + BaseEntity baseEntity = this.bone.getActiveModel().getModeledEntity().getBase(); + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return baseEntity.hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, @NotNull InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, entity, new Vector(0, 0, 0), hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact(this, player.getBukkitEntity(), hand == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND); + + return (InteractionResult)(switch (result) { + case SUCCESS -> InteractionResult.SUCCESS_SERVER; + case SUCCESS_NO_ITEM_USED -> InteractionResult.TRY_WITH_EMPTY_HAND; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.SUCCESS; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }); + } + } + + public boolean shouldBeSaved() { + return false; + } + + @NotNull + public CraftEntity getBukkitEntity() { + CraftEntity bukkitEntity = this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + CraftEntity var5 = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(var5); + return var5; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(@NotNull RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/hitbox/OBB.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/hitbox/OBB.java new file mode 100644 index 0000000..0736093 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R6.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..9491ea9 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R6.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..ea2fe37 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R6.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/GroundNavigationWrapper.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..9f7368e --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R6.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..8ce2949 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R6.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..70e48e6 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_21_R6.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/ModelEngineChannelHandler.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..7547fd5 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/ModelEngineChannelHandler.java @@ -0,0 +1,457 @@ +package com.ticxo.modelengine.v1_21_R6.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R6.NMSFields; +import com.ticxo.modelengine.v1_21_R6.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R6.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntList; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundEntityPositionSyncPacket.class, this::handlePositionSync) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove) + .register(ServerboundClientTickEndPacket.class, this::handleClientTickEnd); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet rawPacket && asClientPacket(rawPacket) instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + Collection> post = this.writeInterceptors.acceptPost(result); + if (!post.isEmpty()) { + list.addAll(post); + } + } + } + + if (!list.isEmpty()) { + Packet var12 = new ClientboundBundlePacket(list); + super.write(ctx, var12, promise); + } + } else { + Packet var13 = this.writeInterceptors.accept(packet); + if (var13 == null) { + return; + } + + Collection> post = this.writeInterceptors.acceptPost(var13); + if (post.isEmpty()) { + super.write(ctx, var13, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var13); + list.addAll(post); + Packet var14 = new ClientboundBundlePacket(list); + super.write(ctx, var14, promise); + } + } + } catch (Throwable var11) { + var11.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List> handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List> handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + List> list = null; + Optional maybeMount = model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT); + if (maybeMount.isPresent() && maybeMount.get() instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + MountRenderer.Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + if (mount == null) { + return null; + } + + CollectionDataTracker ids = mount.getPassengers(); + list = new ArrayList<>(); + list.add(new ClientboundSetPassengersPacket(EntityContainer.of(mount.getMountId(), ids))); + } + } + + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + IntList ids = packet.getEntityIds(); + + for (int i = 0; i < ids.size(); i++) { + this.markViewersDirty(ids.getInt(i)); + } + + int[] set = packet.getEntityIds().intStream().filter(id -> ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE).toArray(); + return set.length == packet.getEntityIds().size() ? packet : new ClientboundRemoveEntitiesPacket(IntArrayList.wrap(set)); + } + + private > T handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readClientbound(packet); + + Packet var4; + try { + int id = buf.readVarInt(); + var4 = ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } finally { + buf.release(); + } + + return (T)var4; + } + + private > T handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundEntityPositionSyncPacket handlePositionSync(ClientboundEntityPositionSyncPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + int id = packet.entityId(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + return !changed ? packet : new ClientboundSetPassengersPacket(EntityContainer.of(packet.getVehicle(), new IntArrayList(merged))); + } + } + } + + private Packet handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readServerbound(packet); + + int entityId; + int action; + try { + entityId = buf.readVarInt(); + action = buf.readVarInt(); + } finally { + buf.release(); + } + + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), action, packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, action, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, action, packet) : packet); + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountController.MountInput input = controller.getInput(); + if (input == null) { + controller.setInput( + new MountController.MountInput( + inputPacket.input().forward(), + inputPacket.input().backward(), + inputPacket.input().left(), + inputPacket.input().right(), + inputPacket.input().jump(), + inputPacket.input().shift(), + inputPacket.input().sprint() + ) + ); + } else { + input.setForward(inputPacket.input().forward()); + input.setBackward(inputPacket.input().backward()); + input.setLeft(inputPacket.input().left()); + input.setRight(inputPacket.input().right()); + input.setJump(inputPacket.input().jump()); + input.setSneak(inputPacket.input().shift()); + input.setSprint(inputPacket.input().sprint()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + if (!ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + private ServerboundClientTickEndPacket handleClientTickEnd(ServerboundClientTickEndPacket packet) { + if (ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + @SuppressWarnings("unchecked") + private static Packet asClientPacket(Object packet) { + return (Packet)packet; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/NetworkHandlerImpl.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..7bd7833 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/NetworkHandlerImpl.java @@ -0,0 +1,141 @@ +package com.ticxo.modelengine.v1_21_R6.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R6.NMSFields; +import com.ticxo.modelengine.v1_21_R6.network.utils.Bundler; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection> collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/patch/PatchedServerGamePacketListener.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..710d9d1 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,439 @@ +package com.ticxo.modelengine.v1_21_R6.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R6.NMSMethods; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.SwingSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(final ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().level()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.level(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + ModelBone hitBone = null; + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel == null) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(interactPacket.getRelayedId()); + if (hitbox != null) { + hitBone = hitbox.getBone(); + activeModel = hitBone.getActiveModel(); + } + } + + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + final ActiveModel finalActiveModel = activeModel; + final ModelBone finalHitBone = hitBone; + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + null, + finalHitBone + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + position, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + position, + finalHitBone + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.ATTACK, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, null); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, pos); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent( + craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND, null + ); + } + } + ); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= player.entityInteractionRange() * player.entityInteractionRange())) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelectedItem().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem)) { + if (player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + ServerEntity serverEntity = entity.moonrise$getTrackedEntity().serverEntity; + List> list = new ArrayList<>(); + serverEntity.sendPairingData(player, list::add); + player.connection.send(new ClientboundBundlePacket(list)); + } + + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem) { + List> data = entity.getEntityData().packAll(); + if (data != null && player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + player.connection.send(new ClientboundSetEntityDataPacket(entity.getId(), data)); + } + + if (entity instanceof Allay allay) { + List> equipment = Arrays.stream(EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.getItemBySlot(slot))) + .collect(Collectors.toList()); + connection.send(new ClientboundSetEquipmentPacket(entity.getId(), equipment)); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.level()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.level(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level().clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.isSameItemSameComponents(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand, + movingobjectpositionblock.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, itemstack, enumhand); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.resyncUsingItem(player); + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent( + CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacketWrapper packet, InteractionHand hand, @Nullable Vec3 vector + ) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.isAttack(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND, + vector != null ? new Vector(vector.x, vector.y, vector.z) : null + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..4d57eaf --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,75 @@ +package com.ticxo.modelengine.v1_21_R6.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper implements Packet { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + private final boolean isAttack; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, int action, ServerboundInteractPacket original) { + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + this.isAttack = action == 1; + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_INTERACT; + } + + public int getEntityId() { + return this.originalId; + } + + public boolean isAttack() { + return this.isAttack; + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/BulkEntityDataEncoder.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..364026e --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R6.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/Bundler.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/Bundler.java new file mode 100644 index 0000000..392a0a9 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_21_R6.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.getLast(); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection> packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.getLast(); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet packet : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/NetworkUtils.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/NetworkUtils.java new file mode 100644 index 0000000..e5b067f --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/NetworkUtils.java @@ -0,0 +1,354 @@ +package com.ticxo.modelengine.v1_21_R6.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R6.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R6.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.GameProtocols.Context; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static final ProtocolInfo CLIENTBOUND_CODEC = GameProtocols.CLIENTBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + public static final ProtocolInfo SERVERBOUND_CODEC = GameProtocols.SERVERBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess()), (Context)() -> false); + private static final Map, Constructor> PACKET_CONSTRUCTOR = new HashMap<>(); + + public static RegistryFriendlyByteBuf createByteBuf() { + return new RegistryFriendlyByteBuf(Unpooled.buffer(), MinecraftServer.getServer().registryAccess()); + } + + public static RegistryFriendlyByteBuf createByteBuf(Consumer consumer) { + RegistryFriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static > T create(Class clazz, RegistryFriendlyByteBuf buf) { + Constructor constructor = PACKET_CONSTRUCTOR.computeIfAbsent(clazz, aClass -> { + try { + Constructor c = aClass.getDeclaredConstructor(RegistryFriendlyByteBuf.class); + c.setAccessible(true); + return c; + } catch (NoSuchMethodException var4x) { + try { + Constructor cx = aClass.getDeclaredConstructor(FriendlyByteBuf.class); + cx.setAccessible(true); + return cx; + } catch (NoSuchMethodException var3) { + throw new RuntimeException(var3); + } + } + }); + + try { + return (T)constructor.newInstance(buf); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException var4) { + throw new RuntimeException(var4); + } + } + + public static FriendlyByteBuf readServerbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + SERVERBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static FriendlyByteBuf readClientbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + CLIENTBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createCameraPivotSpawn(int id, UUID uuid, Vector3f pos, float height) { + ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket( + id, uuid, pos.x, pos.y - height, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createCameraPivotTeleport(int id, Vector3f pos, float height) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - height, pos.z); + ClientboundEntityPositionSyncPacket packet = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createDisplayPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - 0.375, pos.z); + ClientboundEntityPositionSyncPacket tpHigher = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + container = EntityContainer.of(id); + container.setId(id); + container.setPosRaw(pos.x, pos.y - 0.5, pos.z); + ClientboundEntityPositionSyncPacket tpLower = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Object createCameraPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos, float height) { + if (codec == null) { + return createCameraPivotTeleport(id, pos, height); + } else { + return switch (codec.update(pos.x, pos.y - height, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createCameraPivotTeleport(id, pos, height); + }; + } + } + + public static Packets.PacketSupplier createDisplayPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y, pos.z); + return playerUUID -> new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + public static Packets.PacketSupplier lodWrapper( + ModeledEntity modeledEntity, BiFunction> packetFunction + ) { + return uuid -> { + AnimationLODHandler.LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/PacketInterceptor.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..82fa24e --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/PacketInterceptor.java @@ -0,0 +1,84 @@ +package com.ticxo.modelengine.v1_21_R6.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor

    { + private final Map>, PacketInterceptor

    .Modifier>> registry = Maps.newConcurrentMap(); + private final Map>, PacketInterceptor

    .Listener>> postRegistry = Maps.newConcurrentMap(); + + public > PacketInterceptor

    register(Class clazz, Function> function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public > PacketInterceptor

    registerPost(Class clazz, Function>> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor

    .Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection> acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor

    .Listener listener = this.postRegistry.get(original.getClass()); + return (Collection>)(listener != null ? listener.listen(original) : List.of()); + } + } + + class Listener> { + private final Class clazz; + private final Function>> function; + + public Collection> listen(Packet original) { + try { + Collection> collection = this.function.apply(this.clazz.cast(original)); + return (Collection>)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(final Class clazz, final Function>> function) { + this.clazz = clazz; + this.function = function; + } + } + + class Modifier> { + private final Class clazz; + private final Function> function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(final Class clazz, final Function> function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/Packets.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/Packets.java new file mode 100644 index 0000000..c792ea7 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_21_R6.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/HeldItemParser.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..dc1fe31 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/HeldItemParser.java @@ -0,0 +1,186 @@ +package com.ticxo.modelengine.v1_21_R6.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R6.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Quaternionf; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapToInt(HeldItemRenderer.Item::getId)) + )) + ); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Map items = renderer.getRendered(); + IntArrayList entityIds = IntArrayList.toList(items.values().stream().mapToInt(HeldItemRenderer.Item::getId)); + entityIds.add(renderer.getId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + return new ClientboundSetEntityDataPacket(renderer.getId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, HeldItemRenderer.Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(HeldItemRenderer.Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(11); + if (spawn) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, this.viewRange)); + } else if (renderer.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + renderer.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), spawn); + renderer.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), spawn); + renderer.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getRotation() + .ifDirty( + quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf.rotateY((float) Math.PI, new Quaternionf()))), + spawn + ); + renderer.getModel() + .ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + renderer.getDisplay() + .ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getId(), entityData); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location loc = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(loc.getX(), loc.getY(), loc.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + EntityContainer container = EntityContainer.of(renderer.getId()); + container.setPosRaw(loc.getX(), loc.getY(), loc.getZ()); + return new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getId(), renderer.getPassengers())); + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/LeashParser.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/LeashParser.java new file mode 100644 index 0000000..ba1bdbe --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/LeashParser.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.v1_21_R6.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Map leashes = renderer.getRendered(); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(IntArrayList.toList(leashes.values().stream().mapMultiToInt((leash, intConsumer) -> { + intConsumer.accept(leash.getLeashId()); + intConsumer.accept(leash.getPivotId()); + })))); + } + } + + private Packets.PacketSupplier pivotSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + + private ClientboundAddEntityPacket leashSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y - 0.45, pos.z - 0.2, 0.0F, 0.0F, EntityType.BAT, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetEntityDataPacket leashData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getLeashId(), EntityUtils.DEFAULT_BAT_DATA); + } + + private ClientboundSetPassengersPacket mount(LeashRenderer.Leash renderer) { + ArrayList passengers = new ArrayList<>(1); + passengers.add(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), passengers)); + } + + private Object move(LeashRenderer.Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + } + + private ClientboundSetEntityLinkPacket link(LeashRenderer.Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(EntityContainer.of(renderer.getLeashId()), EntityContainer.of(renderer.getConnected().get())); + } + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/MountParser.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/MountParser.java new file mode 100644 index 0000000..bcff32f --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/MountParser.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.v1_21_R6.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R6.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getMountId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Collection mounts = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(mounts.size() * 2); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getMountId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_PIVOT_DISPLAY_DATA); + } + + private ClientboundAddEntityPacket mountSpawn(MountRenderer.Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getMountId())); + } + + private ClientboundSetPassengersPacket mount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getMountId(), renderer.getPassengers())); + } + + private Packets.PacketSupplier pivotMove(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(MountRenderer.Mount renderer) { + return new Rot(renderer.getMountId(), renderer.getYaw().get(), (byte)0, false); + } + + private ClientboundSetEntityDataPacket mountHealth(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, renderer.getHealth().get()))); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(MountRenderer.Mount renderer) { + AttributeInstance attributeInstance = new AttributeInstance(Attributes.MAX_HEALTH, onDirty -> {}); + attributeInstance.setBaseValue(renderer.getMaxHealth().get().floatValue()); + return new ClientboundUpdateAttributesPacket(renderer.getMountId(), Lists.newArrayList(new AttributeInstance[]{attributeInstance})); + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/NameTagParser.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..c82fad4 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/NameTagParser.java @@ -0,0 +1,184 @@ +package com.ticxo.modelengine.v1_21_R6.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTagRenderer.NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTagRenderer.NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Collection nameTags = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(nameTags.size() * 2); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + return !spawn ? null : new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTagRenderer.NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(7); + renderer.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + renderer.getTranslate().ifDirty(flag -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getScale().ifDirty(flag -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getTextOpacity().ifDirty(flag -> entityData.add(new DataValue(26, EntityDataSerializers.BYTE, flag)), spawn); + renderer.getBackgroundColor().ifDirty(flag -> entityData.add(new DataValue(25, EntityDataSerializers.INT, flag)), spawn); + renderer.getStyle().ifDirty(flags -> entityData.add(new DataValue(27, EntityDataSerializers.BYTE, flags)), spawn); + renderer.getLineWidth().ifDirty(flag -> entityData.add(new DataValue(24, EntityDataSerializers.INT, flag)), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new MatchException(null, null); + }; + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, value)); + }, spawn); + renderer.getJsonString() + .ifDirty( + jsonString -> { + if (jsonString == null) { + entityData.add(new DataValue(23, EntityDataSerializers.COMPONENT, Component.empty())); + } else { + entityData.add( + new DataValue(23, EntityDataSerializers.COMPONENT, Optional.ofNullable(CraftChatMessage.fromJSON(jsonString)).orElse(Component.empty())) + ); + } + }, + spawn + ); + renderer.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getTagId(), entityData); + } + } + + private Object pivotMove(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTagRenderer.NameTag renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getTagId())); + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/SegmentParser.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..626482c --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/SegmentParser.java @@ -0,0 +1,205 @@ +package com.ticxo.modelengine.v1_21_R6.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R6.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (SegmentRenderer.Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + IntArrayList destroy = new IntArrayList(); + + for (SegmentRenderer.Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(destroy))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(SegmentRenderer.Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SegmentRenderer.Pivot pivot) { + return new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(SegmentRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(SegmentRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(SegmentRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + ArrayList> entityData = new ArrayList<>(13); + if (force) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } else if (bone.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : 1)), force); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), force); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/SubHitboxParser.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..030f2fd --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/behavior/SubHitboxParser.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R6.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitboxRenderer.SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Collection subHitboxes = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(subHitboxes.size() * 2); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private Object pivotMove(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getHitboxId())); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitboxRenderer.SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitboxRenderer.SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(4); + renderer.getWidth().ifDirty(width -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, width)), spawn); + renderer.getHeight().ifDirty(height -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, height)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getHitboxId(), entityData); + } + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/model/DisplayParser.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/model/DisplayParser.java new file mode 100644 index 0000000..aca1b48 --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/model/DisplayParser.java @@ -0,0 +1,789 @@ +package com.ticxo.modelengine.v1_21_R6.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R6.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static StreamCodec CUSTOM_PAYLOAD_CODEC; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + if (renderer.hasGlowAudience()) { + this.updateAudienceGlow(renderer, data.getTracking().keySet(), data.getStartTracking(), this.noCullForcePlayers); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + private void updateAudienceGlow(DisplayRenderer renderer, Set current, Set startTracking, Set forceUpdates) { + for (DisplayBone bone : renderer.getRendered().values()) { + Set audience = bone.getGlowAudience().get(); + if (audience != null) { + boolean changed = bone.isAudienceGlowDirty(); + if (changed || !startTracking.isEmpty() || !forceUpdates.isEmpty()) { + boolean glowing = bone.getAudienceGlowing().get(); + int color = bone.getAudienceGlowColor().get(); + Set on = new HashSet<>(); + Set off = new HashSet<>(); + if (changed) { + for (UUID uuid : current) { + if (glowing && audience.contains(uuid)) { + on.add(uuid); + } else { + off.add(uuid); + } + } + + bone.clearAudienceGlowDirty(); + } else if (glowing) { + for (UUID uuidx : startTracking) { + if (audience.contains(uuidx)) { + on.add(uuidx); + } + } + + for (UUID uuidxx : forceUpdates) { + if (audience.contains(uuidxx)) { + on.add(uuidxx); + } + } + } + + if (!on.isEmpty() || !off.isEmpty()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + int id = boneData.getId(); + if (!on.isEmpty()) { + NetworkUtils.send(on, this.audienceGlowData(id, true, color)); + } + + if (!off.isEmpty()) { + NetworkUtils.send(off, this.audienceGlowData(id, false, color)); + } + } + } + } + } + } + } + + private ClientboundSetEntityDataPacket audienceGlowData(int entityId, boolean glowing, int color) { + ArrayList> entityData = new ArrayList<>(2); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(glowing ? 96 : 32))); + if (glowing) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + + return new ClientboundSetEntityDataPacket(entityId, entityData); + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + set.add((Packet)this.pivotCameraResize(pivot)); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(destroy)))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(hitboxDestroy)))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)(u -> this.displayData(u, null, boneData, false, transformOnly))); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + AnimationLODHandler.LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + RegistryFriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(RegistryFriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CODEC == null) { + Field field = ClientboundCustomPayloadPacket.class.getField("GAMEPLAY_STREAM_CODEC"); + field.setAccessible(true); + CUSTOM_PAYLOAD_CODEC = (StreamCodec)field.get(null); + } + + return (Packet)CUSTOM_PAYLOAD_CODEC.decode(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData( + BulkEntityDataEncoder encoder, + UUID uuid, + @Nullable AnimationLODHandler.LODTracker tracker, + DisplayBone.BoneData boneData, + boolean force, + boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? new ClientboundSetEntityDataPacket(pivot.getId(), this.cameraPivotData(pivot.getCameraHeight().get())) + : new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private List> cameraPivotData(float height) { + return List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(8, EntityDataSerializers.FLOAT, 0.0F), + new DataValue(9, EntityDataSerializers.FLOAT, height) + ); + } + + private ClientboundSetPassengersPacket pivotMount(DisplayRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(DisplayRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundSetEntityDataPacket pivotCameraResize(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() && pivot.getCameraHeight().isDirty() + ? new ClientboundSetEntityDataPacket(pivot.getId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, pivot.getCameraHeight().get()))) + : null; + } + + private ClientboundAddEntityPacket displaySpawn(DisplayRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData( + UUID uuid, @Nullable AnimationLODHandler.LODTracker tracker, DisplayBone.BoneData boneData, boolean force, boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + ArrayList> entityData = new ArrayList<>(13); + if (!force && update != 0) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : lodTick)), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + entityData.add(new DataValue(16, EntityDataSerializers.INT, val)); + } + }, force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + } + }, force); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + + private ClientboundSetEntityDataPacket displayVisibleData(DisplayBone.BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)))); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color))); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val))); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F))); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)))); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()))); + this.cleanupQueue.add(bone::clearDirty); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(DisplayRenderer.Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(DisplayRenderer.Hitbox hitbox) { + return !hitbox.isPivotVisible() ? null : new ClientboundSetEntityDataPacket(hitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket hitboxSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(4); + hitbox.getWidth().ifDirty(val -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, val)), spawn); + hitbox.getHeight().ifDirty(val -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getHitboxId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(2); + hitbox.getShadowRadius().ifDirty(val -> entityData.add(new DataValue(18, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getShadowId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(DisplayRenderer.Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(DisplayRenderer.Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + return new ClientboundSetPassengersPacket(EntityContainer.of(hitbox.getPivotId(), passengers)); + } + } +} diff --git a/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/vfx/VFXDisplayParser.java b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..916a2ac --- /dev/null +++ b/nms/v1_21_R6/src/main/java/com/ticxo/modelengine/v1_21_R6/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,124 @@ +package com.ticxo.modelengine.v1_21_R6.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R6.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R6.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R6.network.utils.Packets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(new int[]{vfx.getPivotId(), vfx.getModelId()})); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXDisplayRenderer.VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetEntityDataPacket(vfx.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXDisplayRenderer.VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXDisplayRenderer.VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(9); + if (spawn) { + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)32)); + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, 4096.0F)); + entityData.add(new DataValue(24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal())); + } else if (vfx.isModelDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + vfx.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + vfx.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + vfx.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + vfx.clearModelDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(vfx.getModelId(), entityData); + } + } + + private Object teleport(VFXDisplayRenderer.VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetPassengersPacket(EntityContainer.of(vfx.getPivotId(), vfx.getModelId())); + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSFields.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSFields.java new file mode 100644 index 0000000..1f3a1ba --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSFields.java @@ -0,0 +1,59 @@ +package com.ticxo.modelengine.v1_21_R7; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionUtils.ReflectionEnum { + ENTITY_dimensions(Entity.class, "bz", "dimensions"), + ENTITY_eyeHeight(Entity.class, "bA", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "cx", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "bM", "jumping"), + MOB_lookControl(Mob.class, "co", "lookControl"), + MOB_moveControl(Mob.class, "cp", "moveControl"), + MOB_navigation(Mob.class, "cr", "navigation"), + MOB_goalSelector(Mob.class, "cs", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "cA", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "K", "clientIsFloating"), + SERVER_COMMON_PACKET_LISTENER_IMPL_connection(ServerCommonPacketListenerImpl.class, "e", "connection"), + MOVE_CONTROL_operation(MoveControl.class, "k", "operation"), + TRACKED_ENTITY_serverEntity(TrackedEntity.class, "b", "serverEntity"), + TRACKED_ENTITY_range(TrackedEntity.class, "d", "range"), + LEVEL_threadSafeRandom(Level.class, "B", "threadSafeRandom"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "a", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "b", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(final Class target, final String obfuscated, final String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSHandler_v1_21_R7.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSHandler_v1_21_R7.java new file mode 100644 index 0000000..39fb72b --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSHandler_v1_21_R7.java @@ -0,0 +1,231 @@ +package com.ticxo.modelengine.v1_21_R7; + +import com.mojang.math.MatrixUtil; +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.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R7.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v1_21_R7.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R7.parser.behavior.LeashParser; +import com.ticxo.modelengine.v1_21_R7.parser.behavior.MountParser; +import com.ticxo.modelengine.v1_21_R7.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v1_21_R7.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v1_21_R7.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v1_21_R7.parser.model.DisplayParser; +import com.ticxo.modelengine.v1_21_R7.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.components.CustomModelDataComponent; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v1_21_R7 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + private boolean manualTranslucencyOrder; + private boolean forceCMD; + + public NMSHandler_v1_21_R7() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + public void updateConfig() { + this.manualTranslucencyOrder = ConfigProperty.MANUAL_TRANSLUCENCY_ORDER.getBoolean(); + this.forceCMD = ConfigProperty.FORCE_CMD.getBoolean(); + } + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + RegistryFriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, NetworkUtils.create(ClientboundSetPassengersPacket.class, byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public Set createStack(ItemModelData data, ItemModelData.Context context) { + if (this.forceCMD) { + return NMSHandler.super.createStack(data, context); + } else { + ItemStack item = new ItemStack(this.manualTranslucencyOrder && !data.isTranslucent() ? Material.STONE : Material.RED_STAINED_GLASS); + item.editMeta(itemMeta -> { + itemMeta.setItemModel(data.getSingleComposite().model()); + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(context.color())); + if (data.getVariant() != null) { + cmdComp.setStrings(List.of(data.getVariant())); + } + + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return Set.of(item); + } + } + + @Override + public boolean colorStack(ItemStack stack, Color color) { + stack.editMeta(itemMeta -> { + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(color)); + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return true; + } + + @Override + public void applyPlayerHeadItemModel(ItemStack stack) { + stack.editMeta(meta -> meta.setItemModel(this.getPlayerHeadModelKey())); + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(EntityContainer.of(mountId, passengerIds)); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSMethods.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSMethods.java new file mode 100644 index 0000000..45b1982 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/NMSMethods.java @@ -0,0 +1,49 @@ +package com.ticxo.modelengine.v1_21_R7; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.core.HolderLookup.Provider; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements ReflectionUtils.MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "a", "getInstrument", ItemStack.class, Provider.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityContainer.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityContainer.java new file mode 100644 index 0000000..4f6094d --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityContainer.java @@ -0,0 +1,60 @@ +package com.ticxo.modelengine.v1_21_R7.entity; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.network.syncher.SynchedEntityData.Builder; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.ApiStatus.Internal; + +@Internal +public class EntityContainer extends Entity { + public static EntityContainer of(int id) { + return new EntityContainer(id); + } + + public static Entity of(int id, int... passengerIds) { + EntityContainer container = of(id); + container.setPassengers(Arrays.stream(passengerIds).mapToObj(EntityContainer::new).toList()); + return container; + } + + public static Entity of(int id, Collection passengerIds) { + EntityContainer container = of(id); + container.setPassengers(passengerIds.stream().map(EntityContainer::new).toList()); + return container; + } + + private EntityContainer(int id) { + super(EntityType.INTERACTION, MinecraftServer.getServer().overworld()); + this.setId(id); + this.setPosRaw(0.0, 0.0, 0.0); + this.setRot(0.0F, 0.0F); + this.setOnGround(false); + } + + protected void setPassengers(List passengers) { + this.passengers = ImmutableList.copyOf(passengers); + } + + protected void defineSynchedData(@NotNull Builder builder) { + } + + public boolean hurtServer(ServerLevel world, DamageSource source, float amount) { + return false; + } + + protected void readAdditionalSaveData(ValueInput valueInput) { + } + + protected void addAdditionalSaveData(ValueOutput valueOutput) { + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityHandlerImpl.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..c0f3864 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityHandlerImpl.java @@ -0,0 +1,843 @@ +package com.ticxo.modelengine.v1_21_R7.entity; + +import ca.spottedleaf.moonrise.patches.entity_tracker.EntityTrackerEntity; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v1_21_R7.NMSFields; +import com.ticxo.modelengine.v1_21_R7.NMSMethods; +import com.ticxo.modelengine.v1_21_R7.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v1_21_R7.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v1_21_R7.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v1_21_R7.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v1_21_R7.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v1_21_R7.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v1_21_R7.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R7.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v1_21_R7.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v1_21_R7.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.Packets; +import io.papermc.paper.adventure.PaperAdventure; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.kyori.adventure.text.Component; +import net.minecraft.core.Holder; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult.Fail; +import net.minecraft.world.InteractionResult.Pass; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.TryEmptyHandInteraction; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityAttachments; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemUseAnimation; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.World; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public int getEntityId(Entity entity) { + return EntityUtils.nms(entity).getId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + float width = (float)hitbox.getMaxWidth(); + float height = (float)hitbox.getHeight(); + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions(width, height, (float)hitbox.getEyeHeight(), EntityAttachments.createDefault(width, height), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + if (EntityUtils.nms(entity) instanceof LivingEntity living) { + living.getAttributes().registerAttribute(Attributes.STEP_HEIGHT); + Objects.requireNonNull(living.getAttribute(Attributes.STEP_HEIGHT)).setBaseValue(height); + } + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityType.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y - nmsEntity.getVehicleAttachmentPoint(this.dummyArmorStand).y; + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + this.getEntityId(entity), List.of(new DataValue(0, EntityDataSerializers.BYTE, data)) + ); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + switch (oldNav) { + case WallClimberNavigation wallClimberNavigation: + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + break; + case GroundPathNavigation groundPathNavigation: + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + break; + case FlyingPathNavigation flyingPathNavigation: + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + break; + case WaterBoundPathNavigation waterBoundPathNavigation: + newNav = new WaterBoundNavigationWrapper(mob); + break; + case AmphibiousPathNavigation amphibiousPathNavigation: + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + break; + default: + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var13) { + var13.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + World bukkitWorld = location.getWorld(); + if (bukkitWorld == null) { + if (bone.getActiveModel().getModeledEntity().getBase().getOriginal() instanceof Entity entity) { + bukkitWorld = entity.getWorld(); + } + + if (bukkitWorld == null) { + return null; + } + } + + ServerLevel level = ((CraftWorld)bukkitWorld).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity.level() instanceof ServerLevel worldserver) { + return nmsEntity.hurtServer(worldserver, damageSource, amount); + } + } + + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + + @Override + public EntityHandler.InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND + ); + + return switch (result) { + case Success success -> success.equals(net.minecraft.world.InteractionResult.SUCCESS_SERVER) + ? EntityHandler.InteractionResult.SUCCESS + : ( + success.equals(net.minecraft.world.InteractionResult.SUCCESS) + ? EntityHandler.InteractionResult.CONSUME_PARTIAL + : EntityHandler.InteractionResult.CONSUME + ); + case TryEmptyHandInteraction ignored -> EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED; + case Pass ignoredx -> EntityHandler.InteractionResult.PASS; + case Fail ignoredxx -> EntityHandler.InteractionResult.FAIL; + default -> throw new MatchException(null, null); + }; + } else { + return EntityHandler.InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket( + DynamicHitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA + ); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(DynamicHitbox.getHitboxId(), EntityUtils.DEFAULT_SLIME_DATA); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket( + EntityContainer.of(DynamicHitbox.getPivotId(), DynamicHitbox.getHitboxId()) + ); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0, 0.0F, 0.0F + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != ItemUseAnimation.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + player.getEntityId(), List.of(new DataValue(8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3))) + ); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call( + instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack, nmsPlayer.registryAccess() + ); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_threadSafeRandom); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public Float getCameraEyeHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return nmsEntity.getDimensions(Pose.STANDING).eyeHeight(); + } + + @Override + public Float getCameraPivotHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + EntityDimensions dimensions = nmsEntity.getDimensions(nmsEntity.getPose()); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 attachment = ReflectionUtils.call(nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, dimensions, 1.0F); + return attachment == null ? null : (float)(dimensions.eyeHeight() - attachment.y); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public Set getCollidableExemptions(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity living ? living.collidableExemptions : null; + } + + @Override + public Component getCustomName(Entity entity) { + net.minecraft.network.chat.Component name = EntityUtils.nms(entity).getCustomName(); + return name == null ? null : PaperAdventure.asAdventure(name); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + private static Int2ObjectMap getEntityMap(ChunkMap chunkMap) { + return chunkMap.entityMap; + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + if (!ServerInfo.IS_FOLIA && !ServerInfo.IS_PAPER) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = getEntityMap(level.getChunkSource().chunkMap); + if (map == null) { + return new TempTrackedEntity(entity); + } else { + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = getEntityMap(lvl.getChunkSource().chunkMap); + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + } else { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity instanceof EntityTrackerEntity) { + TrackedEntity tracker = nmsEntity.moonrise$getTrackedEntity(); + if (tracker != null) { + return new TrackedEntityImpl(entity, () -> { + net.minecraft.world.entity.Entity current = EntityUtils.nms(entity); + return current instanceof EntityTrackerEntity ? current.moonrise$getTrackedEntity() : null; + }, tracker); + } + } + + return new TempTrackedEntity(entity); + } + } + + @Override + public boolean isGlowing(Entity entity) { + return EntityUtils.nms(entity).getSharedFlag(6); + } + + @Override + public boolean isVisualFire(Entity entity) { + return EntityUtils.nms(entity).getSharedFlag(0); + } + + @Override + public int getFireTicks(Entity entity) { + return this.isVisualFire(entity) ? 1 : 0; + } + + @Override + public BoundingBox getBoundingBox(Entity entity) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + return new BoundingBox(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + boolean jumping = false; + if (JUMPING_GETTER != null && nms instanceof LivingEntity livingEntity) { + try { + jumping = (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var9) { + var9.printStackTrace(); + } + } + + state.jumping = jumping; + state.removed = nms.isRemoved(); + state.glowing = nms.getSharedFlag(6); + state.onFire = nms.getSharedFlag(0); + AABB box = nms.getBoundingBox(); + state.boundingBox.resize(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ); + } + + @Override + public void getLocation(Entity entity, Location location) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + Vec3 pos = nms.position(); + location.setWorld(nms.level().getWorld()); + location.setX(pos.x); + location.setY(pos.y); + location.setZ(pos.z); + location.setYaw(nms.getYRot()); + location.setPitch(nms.getXRot()); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + EntityHandler.BoxRelToCam relX = EntityHandler.BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + EntityHandler.BoxRelToCam relY = EntityHandler.BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + EntityHandler.BoxRelToCam relZ = EntityHandler.BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == EntityHandler.BoxRelToCam.INSIDE && relY == EntityHandler.BoxRelToCam.INSIDE && relZ == EntityHandler.BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.DUST, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (ServerInfo.IS_FOLIA && !Bukkit.isPrimaryThread()) { + return true; + } else if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityMetadataID.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityMetadataID.java new file mode 100644 index 0000000..c413370 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityMetadataID.java @@ -0,0 +1,37 @@ +package com.ticxo.modelengine.v1_21_R7.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_POS_ROT_DURATION = 10; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityUtils.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityUtils.java new file mode 100644 index 0000000..fe4a638 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/EntityUtils.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.v1_21_R7.entity; + +import java.util.List; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.entity.CraftEntity; + +public class EntityUtils { + public static final List> DEFAULT_AREA_EFFECT_CLOUD_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(8, EntityDataSerializers.FLOAT, 0.0F) + ); + public static final List> DEFAULT_PIVOT_DISPLAY_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(10, EntityDataSerializers.INT, 1) + ); + public static final List> DEFAULT_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(16, EntityDataSerializers.INT, 2) + ); + public static final List> DEFAULT_BAT_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE) + ); + public static final List> DEFAULT_ARMOR_STAND_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(15, EntityDataSerializers.BYTE, (byte)16) + ); + + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/OcclusionClipContext.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/OcclusionClipContext.java new file mode 100644 index 0000000..43eecf4 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v1_21_R7.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape() == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (!(tX <= 1.0) && !(tY <= 1.0) && !(tZ <= 1.0)) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/TrackedEntityImpl.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..9698479 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/TrackedEntityImpl.java @@ -0,0 +1,333 @@ +package com.ticxo.modelengine.v1_21_R7.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R7.NMSFields; +import com.ticxo.modelengine.v1_21_R7.NMSMethods; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + Set tracked = this.entity.getTrackedPlayers(); + HashSet set = new HashSet<>(Math.max(8, (int)((tracked.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (Player player : tracked) { + if (this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null && this.playerPredicate.test(playerx) && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + set.add(playerx.getUniqueId()); + } + } + + return set; + } + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + Set tracked = this.entity.getTrackedPlayers(); + HashSet set = new HashSet<>(Math.max(8, (int)((tracked.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (Player player : tracked) { + if (predicate.test(player) && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null + && predicate.test(playerx) + && this.playerPredicate.test(playerx) + && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + set.add(playerx.getUniqueId()); + } + } + + return set; + } + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (Player player : this.entity.getTrackedPlayers()) { + if (predicate.test(player) && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null + && predicate.test(playerx) + && this.playerPredicate.test(playerx) + && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + dest.add(playerx.getUniqueId()); + } + } + + return dest; + } + } + + @Override + public boolean isViewerSetUnchanged() { + if (ServerInfo.IS_FOLIA + || this.mayHaveForced && (!this.forcedPairing.isEmpty() || !this.forcedRemove.isEmpty()) + || this.playerPredicate != DEFAULT_PREDICATE) { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } else if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/BodyRotationControlWrapper.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..6e5c07f --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v1_21_R7.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/LookControlWrapper.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..66feb16 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/LookControlWrapper.java @@ -0,0 +1,152 @@ +package com.ticxo.modelengine.v1_21_R7.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import io.papermc.paper.entity.activation.ActivationRange; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + private MovementOverride movementOverride; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateDirection(this, this.modeledEntity); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/MoveControlWrapper.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..82b396b --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/controller/MoveControlWrapper.java @@ -0,0 +1,272 @@ +package com.ticxo.modelengine.v1_21_R7.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R7.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.Input; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + protected MovementOverride movementOverride; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateMovement(this, modeledEntity); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + if (entity instanceof Player player) { + Input playerInput = player.getCurrentInput(); + controller.setInput( + new MountController.MountInput( + playerInput.isForward(), + playerInput.isBackward(), + playerInput.isLeft(), + playerInput.isRight(), + playerInput.isJump(), + playerInput.isSneak(), + playerInput.isSprint() + ) + ); + } else { + controller.setInput(new MountController.MountInput()); + } + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/hitbox/HitboxEntityImpl.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..ce277f2 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,271 @@ +package com.ticxo.modelengine.v1_21_R7.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.v1_21_R7.NMSFields; +import com.ticxo.modelengine.v1_21_R7.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + @NotNull + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public boolean isInvisible() { + return true; + } + + public void push(@NotNull Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox(Vec3 position) { + if (this.subHitbox == null) { + return super.makeBoundingBox(position); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(@NotNull Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurtServer(@NotNull ServerLevel world, @NotNull DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurtServer(world, source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + BaseEntity baseEntity = this.bone.getActiveModel().getModeledEntity().getBase(); + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return baseEntity.hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, @NotNull InteractionHand hand) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, entity, new Vector(0, 0, 0), hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact(this, player.getBukkitEntity(), hand == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND); + + return (InteractionResult)(switch (result) { + case SUCCESS -> InteractionResult.SUCCESS_SERVER; + case SUCCESS_NO_ITEM_USED -> InteractionResult.TRY_WITH_EMPTY_HAND; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.SUCCESS; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }); + } + } + + public boolean shouldBeSaved() { + return false; + } + + @NotNull + public CraftEntity getBukkitEntity() { + CraftEntity bukkitEntity = this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + CraftEntity var5 = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(var5); + return var5; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(@NotNull RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/hitbox/OBB.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/hitbox/OBB.java new file mode 100644 index 0000000..d760a50 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R7.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..33c2e15 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v1_21_R7.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/FlyingNavigationWrapper.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..d74fc08 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R7.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/GroundNavigationWrapper.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..49f8d95 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R7.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/WallClimberNavigationWrapper.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..e7d1f66 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v1_21_R7.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..d9d9a73 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v1_21_R7.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/ModelEngineChannelHandler.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..c78d431 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/ModelEngineChannelHandler.java @@ -0,0 +1,457 @@ +package com.ticxo.modelengine.v1_21_R7.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R7.NMSFields; +import com.ticxo.modelengine.v1_21_R7.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R7.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntList; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundEntityPositionSyncPacket.class, this::handlePositionSync) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove) + .register(ServerboundClientTickEndPacket.class, this::handleClientTickEnd); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet rawPacket && asClientPacket(rawPacket) instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + Collection> post = this.writeInterceptors.acceptPost(result); + if (!post.isEmpty()) { + list.addAll(post); + } + } + } + + if (!list.isEmpty()) { + Packet var12 = new ClientboundBundlePacket(list); + super.write(ctx, var12, promise); + } + } else { + Packet var13 = this.writeInterceptors.accept(packet); + if (var13 == null) { + return; + } + + Collection> post = this.writeInterceptors.acceptPost(var13); + if (post.isEmpty()) { + super.write(ctx, var13, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var13); + list.addAll(post); + Packet var14 = new ClientboundBundlePacket(list); + super.write(ctx, var14, promise); + } + } + } catch (Throwable var11) { + var11.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List> handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List> handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + List> list = null; + Optional maybeMount = model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT); + if (maybeMount.isPresent() && maybeMount.get() instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + MountRenderer.Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + if (mount == null) { + return null; + } + + CollectionDataTracker ids = mount.getPassengers(); + list = new ArrayList<>(); + list.add(new ClientboundSetPassengersPacket(EntityContainer.of(mount.getMountId(), ids))); + } + } + + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + IntList ids = packet.getEntityIds(); + + for (int i = 0; i < ids.size(); i++) { + this.markViewersDirty(ids.getInt(i)); + } + + int[] set = packet.getEntityIds().intStream().filter(id -> ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE).toArray(); + return set.length == packet.getEntityIds().size() ? packet : new ClientboundRemoveEntitiesPacket(IntArrayList.wrap(set)); + } + + private > T handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readClientbound(packet); + + Packet var4; + try { + int id = buf.readVarInt(); + var4 = ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } finally { + buf.release(); + } + + return (T)var4; + } + + private > T handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundEntityPositionSyncPacket handlePositionSync(ClientboundEntityPositionSyncPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + int id = packet.entityId(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + return !changed ? packet : new ClientboundSetPassengersPacket(EntityContainer.of(packet.getVehicle(), new IntArrayList(merged))); + } + } + } + + private Packet handleInteract(ServerboundInteractPacket packet) { + FriendlyByteBuf buf = NetworkUtils.readServerbound(packet); + + int entityId; + int action; + try { + entityId = buf.readVarInt(); + action = buf.readVarInt(); + } finally { + buf.release(); + } + + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(entityId, hitbox.getTarget(), action, packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(entityId, id, action, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundInteractPacketWrapper(entityId, relayed, action, packet) : packet); + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountController.MountInput input = controller.getInput(); + if (input == null) { + controller.setInput( + new MountController.MountInput( + inputPacket.input().forward(), + inputPacket.input().backward(), + inputPacket.input().left(), + inputPacket.input().right(), + inputPacket.input().jump(), + inputPacket.input().shift(), + inputPacket.input().sprint() + ) + ); + } else { + input.setForward(inputPacket.input().forward()); + input.setBackward(inputPacket.input().backward()); + input.setLeft(inputPacket.input().left()); + input.setRight(inputPacket.input().right()); + input.setJump(inputPacket.input().jump()); + input.setSneak(inputPacket.input().shift()); + input.setSprint(inputPacket.input().sprint()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + if (!ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + private ServerboundClientTickEndPacket handleClientTickEnd(ServerboundClientTickEndPacket packet) { + if (ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + @SuppressWarnings("unchecked") + private static Packet asClientPacket(Object packet) { + return (Packet)packet; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/NetworkHandlerImpl.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..9df4ad8 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/NetworkHandlerImpl.java @@ -0,0 +1,141 @@ +package com.ticxo.modelengine.v1_21_R7.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R7.NMSFields; +import com.ticxo.modelengine.v1_21_R7.network.utils.Bundler; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = ReflectionUtils.get(listener, NMSFields.SERVER_COMMON_PACKET_LISTENER_IMPL_connection); + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection> collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/patch/PatchedServerGamePacketListener.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..53fc309 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,439 @@ +package com.ticxo.modelengine.v1_21_R7.network.patch; + +import com.destroystokyo.paper.event.player.PlayerUseUnknownEntityEvent; +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v1_21_R7.NMSMethods; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.SwingSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.arrow.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.Event.Result; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleInteract(final ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().level()); + final ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + final CraftPlayer craftPlayer = player.getBukkitEntity(); + final ServerLevel serverLevel = player.level(); + final CraftServer craftServer = serverLevel.getServer().server; + final Entity entity = interactPacket.getTarget(serverLevel); + interactPacket.dispatch(new Handler() { + public void onInteraction(InteractionHand hand) { + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, org.bukkit.inventory.EquipmentSlot.OFF_HAND); + } + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + } + + public void onAttack() { + } + }); + if (entity != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + ModelBone hitBone = null; + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(interactPacket.getOriginalId()); + if (activeModel == null) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(interactPacket.getRelayedId()); + if (hitbox != null) { + hitBone = hitbox.getBone(); + activeModel = hitBone.getActiveModel(); + } + } + + if (activeModel != null) { + final BaseEntity base = activeModel.getModeledEntity().getBase(); + final ActiveModel finalActiveModel = activeModel; + final ModelBone finalHitBone = hitBone; + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + null, + finalHitBone + ) + ); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + position, + finalHitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.INTERACT_ON, + org.bukkit.inventory.EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.OFF_HAND), + position, + finalHitBone + ) + ); + } + + public void onAttack() { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + finalActiveModel, + BaseEntityInteractEvent.Action.ATTACK, + org.bukkit.inventory.EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(org.bukkit.inventory.EquipmentSlot.HAND), + null, + finalHitBone + ) + ); + } + } + ); + } + + if (entity == null) { + if (ServerInfo.IS_PAPER) { + interactPacket.dispatch( + new Handler() { + public void onInteraction(InteractionHand hand) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, null); + } + + public void onInteraction(InteractionHand hand, Vec3 pos) { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent(craftServer, craftPlayer, interactPacket, hand, pos); + } + + public void onAttack() { + PatchedServerGamePacketListener.callPlayerUseUnknownEntityEvent( + craftServer, craftPlayer, interactPacket, InteractionHand.MAIN_HAND, null + ); + } + } + ); + } + } else if (serverLevel.getWorldBorder().isWithinBounds(entity.blockPosition())) { + AABB boundingBox = entity.getBoundingBox(); + if (!(boundingBox.distanceToSqr(player.getEyePosition()) >= player.entityInteractionRange() * player.entityInteractionRange())) { + interactPacket.dispatch( + new Handler() { + private void performInteraction( + InteractionHand enumhand, PatchedServerGamePacketListener.EntityInteraction entityInteraction, PlayerInteractEntityEvent event + ) { + ItemStack itemstack = player.getItemInHand(enumhand); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemInHand = player.getItemInHand(enumhand); + boolean triggerLeashUpdate = itemInHand.getItem() == Items.LEAD && entity instanceof Mob; + Item origItem = player.getInventory().getSelectedItem().getItem(); + craftServer.getPluginManager().callEvent(event); + if (entity instanceof Bucketable + && entity instanceof LivingEntity + && origItem.asItem() == Items.WATER_BUCKET + && (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem)) { + if (player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + ServerEntity serverEntity = entity.moonrise$getTrackedEntity().serverEntity; + List> list = new ArrayList<>(); + serverEntity.sendPairingData(player, list::add); + player.connection.send(new ClientboundBundlePacket(list)); + } + + player.containerMenu.sendAllDataToRemote(); + } + + if (triggerLeashUpdate && (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem)) { + connection.send(new ClientboundSetEntityLinkPacket(entity, ((Mob)entity).getLeashHolder())); + } + + if (event.isCancelled() || player.getInventory().getSelectedItem().getItem() != origItem) { + List> data = entity.getEntityData().packAll(); + if (data != null && player.getBukkitEntity().canSee(entity.getBukkitEntity())) { + player.connection.send(new ClientboundSetEntityDataPacket(entity.getId(), data)); + } + + if (entity instanceof Allay allay) { + List> equipment = Arrays.stream(EquipmentSlot.values()) + .map(slot -> Pair.of(slot, allay.getItemBySlot(slot))) + .collect(Collectors.toList()); + connection.send(new ClientboundSetEquipmentPacket(entity.getId(), equipment)); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + player.containerMenu.sendAllDataToRemote(); + return; + } + + InteractionResult enuminteractionresult = entityInteraction.run(player, entity, enumhand); + if (!itemInHand.isEmpty() && itemInHand.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + + if (enuminteractionresult.consumesAction()) { + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, itemstack1, entity); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + + public void onInteraction(@NotNull InteractionHand hand) { + this.performInteraction( + hand, + Player::interactOn, + new PlayerInteractEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onInteraction(@NotNull InteractionHand hand, @NotNull Vec3 pos) { + this.performInteraction( + hand, + (entityplayer, entity1, enumhand1) -> entity1.interactAt(entityplayer, pos, enumhand1), + new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), + entity.getBukkitEntity(), + new Vector(pos.x, pos.y, pos.z), + hand == InteractionHand.OFF_HAND ? org.bukkit.inventory.EquipmentSlot.OFF_HAND : org.bukkit.inventory.EquipmentSlot.HAND + ) + ); + } + + public void onAttack() { + if (!(entity instanceof ItemEntity) + && !(entity instanceof ExperienceOrb) + && !(entity instanceof AbstractArrow) + && (entity != player || player.isSpectator())) { + ItemStack itemstack = player.getItemInHand(InteractionHand.MAIN_HAND); + if (itemstack.isItemEnabled(serverLevel.enabledFeatures())) { + player.attack(entity); + if (!itemstack.isEmpty() && itemstack.getCount() <= -1) { + player.containerMenu.sendAllDataToRemote(); + } + } + } + } + } + ); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.level()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel worldserver = player.level(); + InteractionHand enumhand = packet.getHand(); + ItemStack itemstack = player.getItemInHand(enumhand); + player.resetLastActionTime(); + if (!itemstack.isEmpty() && itemstack.isItemEnabled(worldserver.enabledFeatures())) { + float f1 = player.getXRot(); + float f2 = player.getYRot(); + double d0 = player.getX(); + double d1 = player.getY() + player.getEyeHeight(); + double d2 = player.getZ(); + Vec3 vec3d = new Vec3(d0, d1, d2); + float f3 = Mth.cos(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f4 = Mth.sin(-f2 * (float) (Math.PI / 180.0) - (float) Math.PI); + float f5 = -Mth.cos(-f1 * (float) (Math.PI / 180.0)); + float f6 = Mth.sin(-f1 * (float) (Math.PI / 180.0)); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = player.gameMode.getGameModeForPlayer() == GameType.CREATIVE ? 5.0 : 4.5; + Vec3 vec3d1 = vec3d.add(f7 * d3, f6 * d3, f8 * d3); + HitResult movingobjectposition = player.level().clip(new ClipContext(vec3d, vec3d1, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (movingobjectposition != null && movingobjectposition.getType() == Type.BLOCK) { + BlockHitResult movingobjectpositionblock = (BlockHitResult)movingobjectposition; + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(movingobjectpositionblock.getBlockPos()) + && player.gameMode.interactHand == enumhand + && ItemStack.isSameItemSameComponents(player.gameMode.interactItemStack, itemstack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + Action.RIGHT_CLICK_BLOCK, + movingobjectpositionblock.getBlockPos(), + movingobjectpositionblock.getDirection(), + itemstack, + true, + enumhand, + movingobjectpositionblock.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, itemstack, enumhand); + cancelled = event.useItemInHand() == Result.DENY; + } + + if (cancelled) { + player.resyncUsingItem(player); + player.getBukkitEntity().updateInventory(); + return; + } + + itemstack = player.getItemInHand(enumhand); + if (itemstack.isEmpty()) { + return; + } + + InteractionResult enuminteractionresult = player.gameMode.useItem(player, worldserver, itemstack, enumhand); + afterUse.accept(enuminteractionresult); + if (enuminteractionresult instanceof Success success && success.swingSource() != SwingSource.NONE) { + player.swing(enumhand, success.swingSource() == SwingSource.SERVER); + } + } + } + } + } + } + + private static void callPlayerUseUnknownEntityEvent( + CraftServer cserver, CraftPlayer craftPlayer, ServerboundInteractPacketWrapper packet, InteractionHand hand, @Nullable Vec3 vector + ) { + cserver.getPluginManager() + .callEvent( + new PlayerUseUnknownEntityEvent( + craftPlayer, + packet.getEntityId(), + packet.isAttack(), + hand == InteractionHand.MAIN_HAND ? org.bukkit.inventory.EquipmentSlot.HAND : org.bukkit.inventory.EquipmentSlot.OFF_HAND, + vector != null ? new Vector(vector.x, vector.y, vector.z) : null + ) + ); + } + + @FunctionalInterface + private interface EntityInteraction { + InteractionResult run(ServerPlayer var1, Entity var2, InteractionHand var3); + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/patch/ServerboundInteractPacketWrapper.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..9aedcd4 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,75 @@ +package com.ticxo.modelengine.v1_21_R7.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket.Handler; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class ServerboundInteractPacketWrapper implements Packet { + private final int originalId; + private final int relayedId; + private final ServerboundInteractPacket original; + private final boolean isAttack; + + public ServerboundInteractPacketWrapper(int originalId, int relayedId, int action, ServerboundInteractPacket original) { + this.originalId = originalId; + this.relayedId = relayedId; + this.original = original; + this.isAttack = action == 1; + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_INTERACT; + } + + public int getEntityId() { + return this.originalId; + } + + public boolean isAttack() { + return this.isAttack; + } + + public void handle(ServerGamePacketListener var0) { + PatchedServerGamePacketListener.handleInteract(this, var0); + } + + @Nullable + public Entity getTarget(ServerLevel var0) { + return var0.getEntityOrPart(this.relayedId); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.originalId) != null || tracker.getEntityRelay(this.originalId) != null; + } + + public boolean isUsingSecondaryAction() { + return this.original.isUsingSecondaryAction(); + } + + public void dispatch(Handler var0) { + this.original.dispatch(var0); + } + + public int getOriginalId() { + return this.originalId; + } + + public int getRelayedId() { + return this.relayedId; + } + + public ServerboundInteractPacket getOriginal() { + return this.original; + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/BulkEntityDataEncoder.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..ea87005 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R7.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/Bundler.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/Bundler.java new file mode 100644 index 0000000..db4930f --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v1_21_R7.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.getLast(); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection> packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.getLast(); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet packet : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/NetworkUtils.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/NetworkUtils.java new file mode 100644 index 0000000..af18c33 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/NetworkUtils.java @@ -0,0 +1,354 @@ +package com.ticxo.modelengine.v1_21_R7.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R7.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R7.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.GameProtocols.Context; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static final ProtocolInfo CLIENTBOUND_CODEC = GameProtocols.CLIENTBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + public static final ProtocolInfo SERVERBOUND_CODEC = GameProtocols.SERVERBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess()), (Context)() -> false); + private static final Map, Constructor> PACKET_CONSTRUCTOR = new HashMap<>(); + + public static RegistryFriendlyByteBuf createByteBuf() { + return new RegistryFriendlyByteBuf(Unpooled.buffer(), MinecraftServer.getServer().registryAccess()); + } + + public static RegistryFriendlyByteBuf createByteBuf(Consumer consumer) { + RegistryFriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static > T create(Class clazz, RegistryFriendlyByteBuf buf) { + Constructor constructor = PACKET_CONSTRUCTOR.computeIfAbsent(clazz, aClass -> { + try { + Constructor c = aClass.getDeclaredConstructor(RegistryFriendlyByteBuf.class); + c.setAccessible(true); + return c; + } catch (NoSuchMethodException var4x) { + try { + Constructor cx = aClass.getDeclaredConstructor(FriendlyByteBuf.class); + cx.setAccessible(true); + return cx; + } catch (NoSuchMethodException var3) { + throw new RuntimeException(var3); + } + } + }); + + try { + return (T)constructor.newInstance(buf); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException var4) { + throw new RuntimeException(var4); + } + } + + public static FriendlyByteBuf readServerbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + SERVERBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static FriendlyByteBuf readClientbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + CLIENTBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createCameraPivotSpawn(int id, UUID uuid, Vector3f pos, float height) { + ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket( + id, uuid, pos.x, pos.y - height, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createCameraPivotTeleport(int id, Vector3f pos, float height) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - height, pos.z); + ClientboundEntityPositionSyncPacket packet = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createDisplayPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - 0.375, pos.z); + ClientboundEntityPositionSyncPacket tpHigher = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + container = EntityContainer.of(id); + container.setId(id); + container.setPosRaw(pos.x, pos.y - 0.5, pos.z); + ClientboundEntityPositionSyncPacket tpLower = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Object createCameraPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos, float height) { + if (codec == null) { + return createCameraPivotTeleport(id, pos, height); + } else { + return switch (codec.update(pos.x, pos.y - height, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createCameraPivotTeleport(id, pos, height); + }; + } + } + + public static Packets.PacketSupplier createDisplayPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y, pos.z); + return playerUUID -> new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + public static Packets.PacketSupplier lodWrapper( + ModeledEntity modeledEntity, BiFunction> packetFunction + ) { + return uuid -> { + AnimationLODHandler.LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/PacketInterceptor.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..36b7549 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/PacketInterceptor.java @@ -0,0 +1,84 @@ +package com.ticxo.modelengine.v1_21_R7.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor

    { + private final Map>, PacketInterceptor

    .Modifier>> registry = Maps.newConcurrentMap(); + private final Map>, PacketInterceptor

    .Listener>> postRegistry = Maps.newConcurrentMap(); + + public > PacketInterceptor

    register(Class clazz, Function> function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public > PacketInterceptor

    registerPost(Class clazz, Function>> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor

    .Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection> acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor

    .Listener listener = this.postRegistry.get(original.getClass()); + return (Collection>)(listener != null ? listener.listen(original) : List.of()); + } + } + + class Listener> { + private final Class clazz; + private final Function>> function; + + public Collection> listen(Packet original) { + try { + Collection> collection = this.function.apply(this.clazz.cast(original)); + return (Collection>)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(final Class clazz, final Function>> function) { + this.clazz = clazz; + this.function = function; + } + } + + class Modifier> { + private final Class clazz; + private final Function> function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(final Class clazz, final Function> function) { + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/Packets.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/Packets.java new file mode 100644 index 0000000..294797a --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v1_21_R7.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/HeldItemParser.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..3211311 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/HeldItemParser.java @@ -0,0 +1,186 @@ +package com.ticxo.modelengine.v1_21_R7.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v1_21_R7.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Quaternionf; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapToInt(HeldItemRenderer.Item::getId)) + )) + ); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Map items = renderer.getRendered(); + IntArrayList entityIds = IntArrayList.toList(items.values().stream().mapToInt(HeldItemRenderer.Item::getId)); + entityIds.add(renderer.getId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + return new ClientboundSetEntityDataPacket(renderer.getId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, HeldItemRenderer.Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(HeldItemRenderer.Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(11); + if (spawn) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, this.viewRange)); + } else if (renderer.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + renderer.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), spawn); + renderer.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), spawn); + renderer.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getRotation() + .ifDirty( + quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf.rotateY((float) Math.PI, new Quaternionf()))), + spawn + ); + renderer.getModel() + .ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + renderer.getDisplay() + .ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getId(), entityData); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location loc = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(loc.getX(), loc.getY(), loc.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + EntityContainer container = EntityContainer.of(renderer.getId()); + container.setPosRaw(loc.getX(), loc.getY(), loc.getZ()); + return new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getId(), renderer.getPassengers())); + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/LeashParser.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/LeashParser.java new file mode 100644 index 0000000..ee0ab19 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/LeashParser.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.v1_21_R7.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Map leashes = renderer.getRendered(); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(IntArrayList.toList(leashes.values().stream().mapMultiToInt((leash, intConsumer) -> { + intConsumer.accept(leash.getLeashId()); + intConsumer.accept(leash.getPivotId()); + })))); + } + } + + private Packets.PacketSupplier pivotSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + + private ClientboundAddEntityPacket leashSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y - 0.45, pos.z - 0.2, 0.0F, 0.0F, EntityType.BAT, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetEntityDataPacket leashData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getLeashId(), EntityUtils.DEFAULT_BAT_DATA); + } + + private ClientboundSetPassengersPacket mount(LeashRenderer.Leash renderer) { + ArrayList passengers = new ArrayList<>(1); + passengers.add(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), passengers)); + } + + private Object move(LeashRenderer.Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + } + + private ClientboundSetEntityLinkPacket link(LeashRenderer.Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(EntityContainer.of(renderer.getLeashId()), EntityContainer.of(renderer.getConnected().get())); + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/MountParser.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/MountParser.java new file mode 100644 index 0000000..077de33 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/MountParser.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.v1_21_R7.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R7.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getMountId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Collection mounts = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(mounts.size() * 2); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getMountId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_PIVOT_DISPLAY_DATA); + } + + private ClientboundAddEntityPacket mountSpawn(MountRenderer.Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getMountId())); + } + + private ClientboundSetPassengersPacket mount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getMountId(), renderer.getPassengers())); + } + + private Packets.PacketSupplier pivotMove(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(MountRenderer.Mount renderer) { + return new Rot(renderer.getMountId(), renderer.getYaw().get(), (byte)0, false); + } + + private ClientboundSetEntityDataPacket mountHealth(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, renderer.getHealth().get()))); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(MountRenderer.Mount renderer) { + AttributeInstance attributeInstance = new AttributeInstance(Attributes.MAX_HEALTH, onDirty -> {}); + attributeInstance.setBaseValue(renderer.getMaxHealth().get().floatValue()); + return new ClientboundUpdateAttributesPacket(renderer.getMountId(), Lists.newArrayList(new AttributeInstance[]{attributeInstance})); + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/NameTagParser.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..e7ed59a --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/NameTagParser.java @@ -0,0 +1,184 @@ +package com.ticxo.modelengine.v1_21_R7.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTagRenderer.NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTagRenderer.NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Collection nameTags = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(nameTags.size() * 2); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + return !spawn ? null : new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTagRenderer.NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(7); + renderer.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + renderer.getTranslate().ifDirty(flag -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getScale().ifDirty(flag -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getTextOpacity().ifDirty(flag -> entityData.add(new DataValue(26, EntityDataSerializers.BYTE, flag)), spawn); + renderer.getBackgroundColor().ifDirty(flag -> entityData.add(new DataValue(25, EntityDataSerializers.INT, flag)), spawn); + renderer.getLineWidth().ifDirty(flag -> entityData.add(new DataValue(24, EntityDataSerializers.INT, flag)), spawn); + renderer.getStyle().ifDirty(flags -> entityData.add(new DataValue(27, EntityDataSerializers.BYTE, flags)), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new MatchException(null, null); + }; + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, value)); + }, spawn); + renderer.getJsonString() + .ifDirty( + jsonString -> { + if (jsonString == null) { + entityData.add(new DataValue(23, EntityDataSerializers.COMPONENT, Component.empty())); + } else { + entityData.add( + new DataValue(23, EntityDataSerializers.COMPONENT, Optional.ofNullable(CraftChatMessage.fromJSON(jsonString)).orElse(Component.empty())) + ); + } + }, + spawn + ); + renderer.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getTagId(), entityData); + } + } + + private Object pivotMove(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTagRenderer.NameTag renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getTagId())); + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/SegmentParser.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..6b46205 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/SegmentParser.java @@ -0,0 +1,205 @@ +package com.ticxo.modelengine.v1_21_R7.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R7.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (SegmentRenderer.Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + IntArrayList destroy = new IntArrayList(); + + for (SegmentRenderer.Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(destroy))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(SegmentRenderer.Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SegmentRenderer.Pivot pivot) { + return new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(SegmentRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(SegmentRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(SegmentRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + ArrayList> entityData = new ArrayList<>(13); + if (force) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } else if (bone.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : 1)), force); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), force); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/SubHitboxParser.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..cade986 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/behavior/SubHitboxParser.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v1_21_R7.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitboxRenderer.SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Collection subHitboxes = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(subHitboxes.size() * 2); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private Object pivotMove(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getHitboxId())); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitboxRenderer.SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitboxRenderer.SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(4); + renderer.getWidth().ifDirty(width -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, width)), spawn); + renderer.getHeight().ifDirty(height -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, height)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getHitboxId(), entityData); + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/model/DisplayParser.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/model/DisplayParser.java new file mode 100644 index 0000000..e6438fe --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/model/DisplayParser.java @@ -0,0 +1,789 @@ +package com.ticxo.modelengine.v1_21_R7.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v1_21_R7.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static StreamCodec CUSTOM_PAYLOAD_CODEC; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + if (renderer.hasGlowAudience()) { + this.updateAudienceGlow(renderer, data.getTracking().keySet(), data.getStartTracking(), this.noCullForcePlayers); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + private void updateAudienceGlow(DisplayRenderer renderer, Set current, Set startTracking, Set forceUpdates) { + for (DisplayBone bone : renderer.getRendered().values()) { + Set audience = bone.getGlowAudience().get(); + if (audience != null) { + boolean changed = bone.isAudienceGlowDirty(); + if (changed || !startTracking.isEmpty() || !forceUpdates.isEmpty()) { + boolean glowing = bone.getAudienceGlowing().get(); + int color = bone.getAudienceGlowColor().get(); + Set on = new HashSet<>(); + Set off = new HashSet<>(); + if (changed) { + for (UUID uuid : current) { + if (glowing && audience.contains(uuid)) { + on.add(uuid); + } else { + off.add(uuid); + } + } + + bone.clearAudienceGlowDirty(); + } else if (glowing) { + for (UUID uuidx : startTracking) { + if (audience.contains(uuidx)) { + on.add(uuidx); + } + } + + for (UUID uuidxx : forceUpdates) { + if (audience.contains(uuidxx)) { + on.add(uuidxx); + } + } + } + + if (!on.isEmpty() || !off.isEmpty()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + int id = boneData.getId(); + if (!on.isEmpty()) { + NetworkUtils.send(on, this.audienceGlowData(id, true, color)); + } + + if (!off.isEmpty()) { + NetworkUtils.send(off, this.audienceGlowData(id, false, color)); + } + } + } + } + } + } + } + + private ClientboundSetEntityDataPacket audienceGlowData(int entityId, boolean glowing, int color) { + ArrayList> entityData = new ArrayList<>(2); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(glowing ? 96 : 32))); + if (glowing) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + + return new ClientboundSetEntityDataPacket(entityId, entityData); + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + set.add((Packet)this.pivotCameraResize(pivot)); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(destroy)))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(hitboxDestroy)))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)(u -> this.displayData(u, null, boneData, false, transformOnly))); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + AnimationLODHandler.LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + RegistryFriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(RegistryFriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CODEC == null) { + Field field = ClientboundCustomPayloadPacket.class.getField("GAMEPLAY_STREAM_CODEC"); + field.setAccessible(true); + CUSTOM_PAYLOAD_CODEC = (StreamCodec)field.get(null); + } + + return (Packet)CUSTOM_PAYLOAD_CODEC.decode(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData( + BulkEntityDataEncoder encoder, + UUID uuid, + @Nullable AnimationLODHandler.LODTracker tracker, + DisplayBone.BoneData boneData, + boolean force, + boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + renderer.getRendered().forEach((s, bone) -> { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + }); + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? new ClientboundSetEntityDataPacket(pivot.getId(), this.cameraPivotData(pivot.getCameraHeight().get())) + : new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private List> cameraPivotData(float height) { + return List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(8, EntityDataSerializers.FLOAT, 0.0F), + new DataValue(9, EntityDataSerializers.FLOAT, height) + ); + } + + private ClientboundSetPassengersPacket pivotMount(DisplayRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(DisplayRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundSetEntityDataPacket pivotCameraResize(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() && pivot.getCameraHeight().isDirty() + ? new ClientboundSetEntityDataPacket(pivot.getId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, pivot.getCameraHeight().get()))) + : null; + } + + private ClientboundAddEntityPacket displaySpawn(DisplayRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData( + UUID uuid, @Nullable AnimationLODHandler.LODTracker tracker, DisplayBone.BoneData boneData, boolean force, boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + ArrayList> entityData = new ArrayList<>(13); + if (!force && update != 0) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : lodTick)), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + entityData.add(new DataValue(16, EntityDataSerializers.INT, val)); + } + }, force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + } + }, force); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + + private ClientboundSetEntityDataPacket displayVisibleData(DisplayBone.BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)))); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color))); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val))); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F))); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)))); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()))); + this.cleanupQueue.add(bone::clearDirty); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(DisplayRenderer.Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(DisplayRenderer.Hitbox hitbox) { + return !hitbox.isPivotVisible() ? null : new ClientboundSetEntityDataPacket(hitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket hitboxSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(4); + hitbox.getWidth().ifDirty(val -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, val)), spawn); + hitbox.getHeight().ifDirty(val -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getHitboxId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(2); + hitbox.getShadowRadius().ifDirty(val -> entityData.add(new DataValue(18, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getShadowId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(DisplayRenderer.Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(DisplayRenderer.Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + return new ClientboundSetPassengersPacket(EntityContainer.of(hitbox.getPivotId(), passengers)); + } + } +} diff --git a/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/vfx/VFXDisplayParser.java b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..517f854 --- /dev/null +++ b/nms/v1_21_R7/src/main/java/com/ticxo/modelengine/v1_21_R7/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,124 @@ +package com.ticxo.modelengine.v1_21_R7.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v1_21_R7.entity.EntityContainer; +import com.ticxo.modelengine.v1_21_R7.entity.EntityUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.NetworkUtils; +import com.ticxo.modelengine.v1_21_R7.network.utils.Packets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(new int[]{vfx.getPivotId(), vfx.getModelId()})); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXDisplayRenderer.VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetEntityDataPacket(vfx.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXDisplayRenderer.VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXDisplayRenderer.VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(9); + if (spawn) { + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)32)); + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, 4096.0F)); + entityData.add(new DataValue(24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal())); + } else if (vfx.isModelDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + vfx.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + vfx.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + vfx.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + vfx.clearModelDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(vfx.getModelId(), entityData); + } + } + + private Object teleport(VFXDisplayRenderer.VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetPassengersPacket(EntityContainer.of(vfx.getPivotId(), vfx.getModelId())); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSFields.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSFields.java new file mode 100644 index 0000000..aa56524 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSFields.java @@ -0,0 +1,55 @@ +package com.ticxo.modelengine.v26_1; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionUtils.ReflectionEnum { + ENTITY_dimensions(Entity.class, "dimensions", "dimensions"), + ENTITY_eyeHeight(Entity.class, "eyeHeight", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "noJumpDelay", "noJumpDelay"), + MOB_lookControl(Mob.class, "lookControl", "lookControl"), + MOB_moveControl(Mob.class, "moveControl", "moveControl"), + MOB_navigation(Mob.class, "navigation", "navigation"), + MOB_goalSelector(Mob.class, "goalSelector", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "bodyRotationControl", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "clientIsFloating", "clientIsFloating"), + MOVE_CONTROL_operation(MoveControl.class, "operation", "operation"), + TRACKED_ENTITY_range(TrackedEntity.class, "range", "range"), + LEVEL_soundSeedGenerator(Level.class, "soundSeedGenerator", "soundSeedGenerator"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "entityId", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "entityId", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(final Class target, final String obfuscated, final String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSHandler_v26_1.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSHandler_v26_1.java new file mode 100644 index 0000000..bd9f030 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSHandler_v26_1.java @@ -0,0 +1,231 @@ +package com.ticxo.modelengine.v26_1; + +import com.mojang.math.MatrixUtil; +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.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v26_1.entity.EntityContainer; +import com.ticxo.modelengine.v26_1.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v26_1.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_1.parser.behavior.LeashParser; +import com.ticxo.modelengine.v26_1.parser.behavior.MountParser; +import com.ticxo.modelengine.v26_1.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v26_1.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v26_1.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v26_1.parser.model.DisplayParser; +import com.ticxo.modelengine.v26_1.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.apache.commons.lang3.tuple.Triple; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.components.CustomModelDataComponent; +import org.bukkit.util.Transformation; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Quaternionfc; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +public class NMSHandler_v26_1 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + private boolean manualTranslucencyOrder; + private boolean forceCMD; + + public NMSHandler_v26_1() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + public void updateConfig() { + this.manualTranslucencyOrder = ConfigProperty.MANUAL_TRANSLUCENCY_ORDER.getBoolean(); + this.forceCMD = ConfigProperty.FORCE_CMD.getBoolean(); + } + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + RegistryFriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, NetworkUtils.create(ClientboundSetPassengersPacket.class, byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public Set createStack(ItemModelData data, ItemModelData.Context context) { + if (this.forceCMD) { + return NMSHandler.super.createStack(data, context); + } else { + ItemStack item = new ItemStack(this.manualTranslucencyOrder && !data.isTranslucent() ? Material.GLASS : Material.BONE); + item.editMeta(itemMeta -> { + itemMeta.setItemModel(data.getSingleComposite().model()); + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(context.color())); + if (data.getVariant() != null) { + cmdComp.setStrings(List.of(data.getVariant())); + } + + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return Set.of(item); + } + } + + @Override + public boolean colorStack(ItemStack stack, Color color) { + stack.editMeta(itemMeta -> { + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(color)); + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return true; + } + + @Override + public void applyPlayerHeadItemModel(ItemStack stack) { + stack.editMeta(meta -> meta.setItemModel(this.getPlayerHeadModelKey())); + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(EntityContainer.of(mountId, passengerIds)); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + float f = 1.0F / transform.m33(); + Triple triple = MatrixUtil.svdDecompose(new Matrix3f(transform).scale(f)); + return new Transformation( + transform.getTranslation(new Vector3f()).mul(f), + new Quaternionf((Quaternionfc)triple.getLeft()), + new Vector3f((Vector3fc)triple.getMiddle()), + new Quaternionf((Quaternionfc)triple.getRight()) + ); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSMethods.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSMethods.java new file mode 100644 index 0000000..2dbb6a0 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/NMSMethods.java @@ -0,0 +1,49 @@ +package com.ticxo.modelengine.v26_1; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.core.HolderLookup.Provider; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements ReflectionUtils.MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "a", "getInstrument", ItemStack.class, Provider.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityContainer.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityContainer.java new file mode 100644 index 0000000..29bb442 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityContainer.java @@ -0,0 +1,60 @@ +package com.ticxo.modelengine.v26_1.entity; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.network.syncher.SynchedEntityData.Builder; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.ApiStatus.Internal; + +@Internal +public class EntityContainer extends Entity { + public static EntityContainer of(int id) { + return new EntityContainer(id); + } + + public static Entity of(int id, int... passengerIds) { + EntityContainer container = of(id); + container.setPassengers(Arrays.stream(passengerIds).mapToObj(EntityContainer::new).toList()); + return container; + } + + public static Entity of(int id, Collection passengerIds) { + EntityContainer container = of(id); + container.setPassengers(passengerIds.stream().map(EntityContainer::new).toList()); + return container; + } + + private EntityContainer(int id) { + super(EntityType.INTERACTION, MinecraftServer.getServer().overworld()); + this.setId(id); + this.setPosRaw(0.0, 0.0, 0.0); + this.setRot(0.0F, 0.0F); + this.setOnGround(false); + } + + protected void setPassengers(List passengers) { + this.passengers = ImmutableList.copyOf(passengers); + } + + protected void defineSynchedData(@NotNull Builder builder) { + } + + public boolean hurtServer(ServerLevel world, DamageSource source, float amount) { + return false; + } + + protected void readAdditionalSaveData(ValueInput valueInput) { + } + + protected void addAdditionalSaveData(ValueOutput valueOutput) { + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityHandlerImpl.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..5f388b4 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityHandlerImpl.java @@ -0,0 +1,821 @@ +package com.ticxo.modelengine.v26_1.entity; + +import ca.spottedleaf.moonrise.patches.entity_tracker.EntityTrackerEntity; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v26_1.NMSFields; +import com.ticxo.modelengine.v26_1.NMSMethods; +import com.ticxo.modelengine.v26_1.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v26_1.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v26_1.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v26_1.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v26_1.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v26_1.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v26_1.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v26_1.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v26_1.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v26_1.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_1.network.utils.Packets; +import io.papermc.paper.adventure.PaperAdventure; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.kyori.adventure.text.Component; +import net.minecraft.core.Holder; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult.Fail; +import net.minecraft.world.InteractionResult.Pass; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.TryEmptyHandInteraction; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityAttachments; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemUseAnimation; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.World; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(); + } + + @Override + public int getEntityId(Entity entity) { + return EntityUtils.nms(entity).getId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + float width = (float)hitbox.getMaxWidth(); + float height = (float)hitbox.getHeight(); + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions(width, height, (float)hitbox.getEyeHeight(), EntityAttachments.createDefault(width, height), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + if (EntityUtils.nms(entity) instanceof LivingEntity living) { + living.getAttributes().registerAttribute(Attributes.STEP_HEIGHT); + Objects.requireNonNull(living.getAttribute(Attributes.STEP_HEIGHT)).setBaseValue(height); + } + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityType.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y - nmsEntity.getVehicleAttachmentPoint(this.dummyArmorStand).y; + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + this.getEntityId(entity), List.of(new DataValue(0, EntityDataSerializers.BYTE, data)) + ); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + switch (oldNav) { + case WallClimberNavigation wallClimberNavigation: + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + break; + case GroundPathNavigation groundPathNavigation: + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + break; + case FlyingPathNavigation flyingPathNavigation: + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + break; + case WaterBoundPathNavigation waterBoundPathNavigation: + newNav = new WaterBoundNavigationWrapper(mob); + break; + case AmphibiousPathNavigation amphibiousPathNavigation: + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + break; + default: + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var13) { + var13.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + World bukkitWorld = location.getWorld(); + if (bukkitWorld == null) { + if (bone.getActiveModel().getModeledEntity().getBase().getOriginal() instanceof Entity entity) { + bukkitWorld = entity.getWorld(); + } + + if (bukkitWorld == null) { + return null; + } + } + + ServerLevel level = ((CraftWorld)bukkitWorld).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + if (!entity.isRemoved() && entity.isValid()) { + int attempts = 0; + + while (level.getEntity(entity.getUUID()) != null && attempts++ < 8) { + entity.setUUID(UUID.randomUUID()); + } + + if (level.getEntity(entity.getUUID()) != null) { + entity.discard(); + } else { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + } + } + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity.level() instanceof ServerLevel worldserver) { + return nmsEntity.hurtServer(worldserver, damageSource, amount); + } + } + + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + + @Override + public EntityHandler.InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, Vec3.ZERO + ); + + return switch (result) { + case Success success -> success.equals(net.minecraft.world.InteractionResult.SUCCESS_SERVER) + ? EntityHandler.InteractionResult.SUCCESS + : ( + success.equals(net.minecraft.world.InteractionResult.SUCCESS) + ? EntityHandler.InteractionResult.CONSUME_PARTIAL + : EntityHandler.InteractionResult.CONSUME + ); + case TryEmptyHandInteraction ignored -> EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED; + case Pass ignoredx -> EntityHandler.InteractionResult.PASS; + case Fail ignoredxx -> EntityHandler.InteractionResult.FAIL; + default -> throw new MatchException(null, null); + }; + } else { + return EntityHandler.InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket( + DynamicHitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA + ); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityType.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(DynamicHitbox.getHitboxId(), EntityUtils.DEFAULT_SLIME_DATA); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket( + EntityContainer.of(DynamicHitbox.getPivotId(), DynamicHitbox.getHitboxId()) + ); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + Objects.requireNonNull(EntityHandlerImpl.this); + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0, nmsPlayer.getYRot(), nmsPlayer.getXRot() + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != ItemUseAnimation.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + player.getEntityId(), List.of(new DataValue(8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3))) + ); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call( + instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack, nmsPlayer.registryAccess() + ); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_soundSeedGenerator); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.jumping : false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public Float getCameraEyeHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return nmsEntity.getDimensions(Pose.STANDING).eyeHeight(); + } + + @Override + public Float getCameraPivotHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + EntityDimensions dimensions = nmsEntity.getDimensions(nmsEntity.getPose()); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityType.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 attachment = ReflectionUtils.call(nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, dimensions, 1.0F); + return attachment == null ? null : (float)(dimensions.eyeHeight() - attachment.y); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public Set getCollidableExemptions(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity living ? living.collidableExemptions : null; + } + + @Override + public Component getCustomName(Entity entity) { + net.minecraft.network.chat.Component name = EntityUtils.nms(entity).getCustomName(); + return name == null ? null : PaperAdventure.asAdventure(name); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + private static Int2ObjectMap getEntityMap(ChunkMap chunkMap) { + return chunkMap.entityMap; + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + if (!ServerInfo.IS_FOLIA && !ServerInfo.IS_PAPER) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = getEntityMap(level.getChunkSource().chunkMap); + if (map == null) { + return new TempTrackedEntity(entity); + } else { + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = getEntityMap(lvl.getChunkSource().chunkMap); + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + } else { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity instanceof EntityTrackerEntity) { + TrackedEntity tracker = nmsEntity.moonrise$getTrackedEntity(); + if (tracker != null) { + return new TrackedEntityImpl(entity, () -> { + net.minecraft.world.entity.Entity current = EntityUtils.nms(entity); + return current instanceof EntityTrackerEntity ? current.moonrise$getTrackedEntity() : null; + }, tracker); + } + } + + return new TempTrackedEntity(entity); + } + } + + @Override + public boolean isGlowing(Entity entity) { + return EntityUtils.nms(entity).getSharedFlag(6); + } + + @Override + public boolean isVisualFire(Entity entity) { + return EntityUtils.nms(entity).getSharedFlag(0); + } + + @Override + public int getFireTicks(Entity entity) { + return this.isVisualFire(entity) ? 1 : 0; + } + + @Override + public BoundingBox getBoundingBox(Entity entity) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + return new BoundingBox(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public void getLocation(Entity entity, Location location) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + Vec3 pos = nms.position(); + location.setWorld(nms.level().getWorld()); + location.setX(pos.x); + location.setY(pos.y); + location.setZ(pos.z); + location.setYaw(nms.getYRot()); + location.setPitch(nms.getXRot()); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + EntityHandler.BoxRelToCam relX = EntityHandler.BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + EntityHandler.BoxRelToCam relY = EntityHandler.BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + EntityHandler.BoxRelToCam relZ = EntityHandler.BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == EntityHandler.BoxRelToCam.INSIDE && relY == EntityHandler.BoxRelToCam.INSIDE && relZ == EntityHandler.BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.DUST, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (ServerInfo.IS_FOLIA && !Bukkit.isPrimaryThread()) { + return true; + } else if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityMetadataID.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityMetadataID.java new file mode 100644 index 0000000..2900dd1 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityMetadataID.java @@ -0,0 +1,37 @@ +package com.ticxo.modelengine.v26_1.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_POS_ROT_DURATION = 10; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 16; +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityUtils.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityUtils.java new file mode 100644 index 0000000..8752a11 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/EntityUtils.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.v26_1.entity; + +import java.util.List; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.entity.CraftEntity; + +public class EntityUtils { + public static final List> DEFAULT_AREA_EFFECT_CLOUD_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(8, EntityDataSerializers.FLOAT, 0.0F) + ); + public static final List> DEFAULT_PIVOT_DISPLAY_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(10, EntityDataSerializers.INT, 1) + ); + public static final List> DEFAULT_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(16, EntityDataSerializers.INT, 2) + ); + public static final List> DEFAULT_BAT_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE) + ); + public static final List> DEFAULT_ARMOR_STAND_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(15, EntityDataSerializers.BYTE, (byte)16) + ); + + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/OcclusionClipContext.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/OcclusionClipContext.java new file mode 100644 index 0000000..3f26b59 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v26_1.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape() == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (!(tX <= 1.0) && !(tY <= 1.0) && !(tZ <= 1.0)) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/TrackedEntityImpl.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..afbb8f7 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/TrackedEntityImpl.java @@ -0,0 +1,333 @@ +package com.ticxo.modelengine.v26_1.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v26_1.NMSFields; +import com.ticxo.modelengine.v26_1.NMSMethods; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + Set tracked = this.entity.getTrackedPlayers(); + HashSet set = new HashSet<>(Math.max(8, (int)((tracked.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (Player player : tracked) { + if (this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null && this.playerPredicate.test(playerx) && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + set.add(playerx.getUniqueId()); + } + } + + return set; + } + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + Set tracked = this.entity.getTrackedPlayers(); + HashSet set = new HashSet<>(Math.max(8, (int)((tracked.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (Player player : tracked) { + if (predicate.test(player) && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null + && predicate.test(playerx) + && this.playerPredicate.test(playerx) + && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + set.add(playerx.getUniqueId()); + } + } + + return set; + } + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (Player player : this.entity.getTrackedPlayers()) { + if (predicate.test(player) && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null + && predicate.test(playerx) + && this.playerPredicate.test(playerx) + && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + dest.add(playerx.getUniqueId()); + } + } + + return dest; + } + } + + @Override + public boolean isViewerSetUnchanged() { + if (ServerInfo.IS_FOLIA + || this.mayHaveForced && (!this.forcedPairing.isEmpty() || !this.forcedRemove.isEmpty()) + || this.playerPredicate != DEFAULT_PREDICATE) { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } else if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/BodyRotationControlWrapper.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..64d8d61 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v26_1.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/LookControlWrapper.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..7efc6f9 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/LookControlWrapper.java @@ -0,0 +1,152 @@ +package com.ticxo.modelengine.v26_1.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import io.papermc.paper.entity.activation.ActivationRange; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + private MovementOverride movementOverride; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateDirection(this, this.modeledEntity); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/MoveControlWrapper.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..b7a6ffd --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/controller/MoveControlWrapper.java @@ -0,0 +1,272 @@ +package com.ticxo.modelengine.v26_1.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_1.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.Input; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + protected MovementOverride movementOverride; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateMovement(this, modeledEntity); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + if (entity instanceof Player player) { + Input playerInput = player.getCurrentInput(); + controller.setInput( + new MountController.MountInput( + playerInput.isForward(), + playerInput.isBackward(), + playerInput.isLeft(), + playerInput.isRight(), + playerInput.isJump(), + playerInput.isSneak(), + playerInput.isSprint() + ) + ); + } else { + controller.setInput(new MountController.MountInput()); + } + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/hitbox/HitboxEntityImpl.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..0ee2b08 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,288 @@ +package com.ticxo.modelengine.v26_1.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v26_1.NMSFields; +import com.ticxo.modelengine.v26_1.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; +import org.jspecify.annotations.NonNull; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityType.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + public boolean canBeHitByProjectile() { + return this.subHitbox.isCanBeHitByProjectile(); + } + + @NotNull + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public boolean isInvisible() { + return true; + } + + public void push(@NotNull Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox(Vec3 position) { + if (this.subHitbox == null) { + return super.makeBoundingBox(position); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(@NotNull Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurtServer(@NotNull ServerLevel world, @NotNull DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurtServer(world, source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + BaseEntity baseEntity = this.bone.getActiveModel().getModeledEntity().getBase(); + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return baseEntity.hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, @NotNull InteractionHand hand, @NonNull Vec3 location) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, entity, new Vector(0, 0, 0), hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand, location); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact(this, player.getBukkitEntity(), hand == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND); + + return (InteractionResult)(switch (result) { + case SUCCESS -> InteractionResult.SUCCESS_SERVER; + case SUCCESS_NO_ITEM_USED -> InteractionResult.TRY_WITH_EMPTY_HAND; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.SUCCESS; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }); + } + } + + public boolean shouldBeSaved() { + return false; + } + + @NotNull + public CraftEntity getBukkitEntity() { + CraftEntity bukkitEntity = this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + CraftEntity var5 = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(var5); + return var5; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(@NotNull RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + if (!this.markRemoved) { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + + try { + Promise.start(this.getBukkitEntity()).thenRunSync(() -> { + if (!this.isRemoved()) { + this.discard(); + } + }); + } catch (Throwable var2) { + } + } + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/hitbox/OBB.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/hitbox/OBB.java new file mode 100644 index 0000000..87b97a4 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v26_1.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..1f9875e --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v26_1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/FlyingNavigationWrapper.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..f850225 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v26_1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/GroundNavigationWrapper.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..5d72f9c --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v26_1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/WallClimberNavigationWrapper.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..f115187 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v26_1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..581b238 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v26_1.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/ModelEngineChannelHandler.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..aac82f1 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/ModelEngineChannelHandler.java @@ -0,0 +1,474 @@ +package com.ticxo.modelengine.v26_1.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_1.NMSFields; +import com.ticxo.modelengine.v26_1.entity.EntityContainer; +import com.ticxo.modelengine.v26_1.network.patch.ServerboundAttackPacketWrapper; +import com.ticxo.modelengine.v26_1.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_1.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntList; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundAttackPacket; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundEntityPositionSyncPacket.class, this::handlePositionSync) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundAttackPacket.class, this::handleAttack) + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove) + .register(ServerboundClientTickEndPacket.class, this::handleClientTickEnd); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet rawPacket && asClientPacket(rawPacket) instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + Collection> post = this.writeInterceptors.acceptPost(result); + if (!post.isEmpty()) { + list.addAll(post); + } + } + } + + if (!list.isEmpty()) { + Packet var12 = new ClientboundBundlePacket(list); + super.write(ctx, var12, promise); + } + } else { + Packet var13 = this.writeInterceptors.accept(packet); + if (var13 == null) { + return; + } + + Collection> post = this.writeInterceptors.acceptPost(var13); + if (post.isEmpty()) { + super.write(ctx, var13, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var13); + list.addAll(post); + Packet var14 = new ClientboundBundlePacket(list); + super.write(ctx, var14, promise); + } + } + } catch (Throwable var11) { + var11.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List> handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List> handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + List> list = null; + Optional maybeMount = model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT); + if (maybeMount.isPresent() && maybeMount.get() instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + MountRenderer.Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + if (mount == null) { + return null; + } + + CollectionDataTracker ids = mount.getPassengers(); + list = new ArrayList<>(); + list.add(new ClientboundSetPassengersPacket(EntityContainer.of(mount.getMountId(), ids))); + } + } + + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + IntList ids = packet.getEntityIds(); + + for (int i = 0; i < ids.size(); i++) { + this.markViewersDirty(ids.getInt(i)); + } + + int[] set = packet.getEntityIds().intStream().filter(id -> ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE).toArray(); + return set.length == packet.getEntityIds().size() ? packet : new ClientboundRemoveEntitiesPacket(IntArrayList.wrap(set)); + } + + private > T handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readClientbound(packet); + + Packet var4; + try { + int id = buf.readVarInt(); + var4 = ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } finally { + buf.release(); + } + + return (T)var4; + } + + private > T handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundEntityPositionSyncPacket handlePositionSync(ClientboundEntityPositionSyncPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + int id = packet.entityId(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + return !changed ? packet : new ClientboundSetPassengersPacket(EntityContainer.of(packet.getVehicle(), new IntArrayList(merged))); + } + } + } + + private Packet handleAttack(ServerboundAttackPacket packet) { + int entityId = packet.entityId(); + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundAttackPacketWrapper(hitbox.getTarget(), packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundAttackPacketWrapper(id, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundAttackPacketWrapper(relayed, packet) : packet); + } + } + + private Packet handleInteract(ServerboundInteractPacket packet) { + int entityId = packet.entityId(); + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(hitbox.getTarget(), packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(id, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundInteractPacketWrapper(relayed, packet) : packet); + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountController.MountInput input = controller.getInput(); + if (input == null) { + controller.setInput( + new MountController.MountInput( + inputPacket.input().forward(), + inputPacket.input().backward(), + inputPacket.input().left(), + inputPacket.input().right(), + inputPacket.input().jump(), + inputPacket.input().shift(), + inputPacket.input().sprint() + ) + ); + } else { + input.setForward(inputPacket.input().forward()); + input.setBackward(inputPacket.input().backward()); + input.setLeft(inputPacket.input().left()); + input.setRight(inputPacket.input().right()); + input.setJump(inputPacket.input().jump()); + input.setSneak(inputPacket.input().shift()); + input.setSprint(inputPacket.input().sprint()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + if (!ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + private ServerboundClientTickEndPacket handleClientTickEnd(ServerboundClientTickEndPacket packet) { + if (ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + @SuppressWarnings("unchecked") + private static Packet asClientPacket(Object packet) { + return (Packet)packet; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/NetworkHandlerImpl.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..6027d7e --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/NetworkHandlerImpl.java @@ -0,0 +1,139 @@ +package com.ticxo.modelengine.v26_1.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.v26_1.network.utils.Bundler; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = listener.connection; + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = listener.connection; + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection> collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/PatchedServerGamePacketListener.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..1d4b6a5 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,389 @@ +package com.ticxo.modelengine.v26_1.network.patch; + +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v26_1.NMSMethods; +import io.papermc.paper.configuration.GlobalConfiguration; +import io.papermc.paper.util.MCUtil; +import java.util.Arrays; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.SwingSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.Leashable; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.animal.Bucketable; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.animal.equine.AbstractHorse; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.projectile.arrow.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.CraftEquipmentSlot; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.event.Event.Result; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerKickEvent.Cause; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleAttack(ServerboundAttackPacketWrapper attackPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(attackPacket, connection, connection.getPlayer().level()); + ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + if (connection.hasClientLoaded()) { + CraftPlayer craftPlayer = player.getBukkitEntity(); + ServerLevel level = player.level(); + CraftServer craftServer = level.getServer().server; + Entity target = level.getEntityOrPart(attackPacket.getRelayedId()); + if (target != player || player.isSpectator()) { + player.resetLastActionTime(); + callBaseEntityEvents( + attackPacket, + (base, model, hitBone) -> craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.ATTACK, + EquipmentSlot.HAND, + player.isShiftKeyDown(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null, + hitBone + ) + ) + ); + if (target != null && level.getWorldBorder().isWithinBounds(target.blockPosition())) { + AABB targetBounds = target.getBoundingBox(); + ItemStack mainHandItem = player.getMainHandItem(); + if (player.isWithinAttackRange(mainHandItem, targetBounds, GlobalConfiguration.get().misc.clientInteractionLeniencyDistance.or(3.0)) + && !mainHandItem.has(DataComponents.PIERCING_WEAPON)) { + if (target instanceof ItemEntity + || target instanceof ExperienceOrb + || target == player + || target instanceof AbstractArrow abstractArrow && !abstractArrow.isAttackable()) { + connection.disconnect(Component.translatable("multiplayer.disconnect.invalid_entity_attacked"), Cause.INVALID_ENTITY_ATTACKED); + LOGGER.warn("Player {} tried to attack an invalid entity", player.getPlainTextName()); + } else if (mainHandItem.isItemEnabled(level.enabledFeatures()) && !player.cannotAttackWithItem(mainHandItem, 5)) { + player.attack(target); + } + } + } else if (target == null) { + CraftEventFactory.callPlayerUseUnknownEntityEvent(player, attackPacket.getOriginalId(), true, InteractionHand.MAIN_HAND, null); + } + + if (GlobalConfiguration.get().unsupportedSettings.updateEquipmentOnPlayerActions) { + player.detectEquipmentUpdates(); + } + } + } + } + } + } + + public static void handleInteract(ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().level()); + ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + if (connection.hasClientLoaded()) { + CraftPlayer craftPlayer = player.getBukkitEntity(); + ServerLevel level = player.level(); + CraftServer craftServer = level.getServer().server; + Entity target = level.getEntityOrPart(interactPacket.getRelayedId()); + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.OFF_HAND); + } + + if (target != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + callBaseEntityEvents( + interactPacket, + (base, model, hitBone) -> { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null, + hitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + null, + hitBone + ) + ); + Vec3 pos = interactPacket.getLocation(); + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT_ON, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + position, + hitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT_ON, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + position, + hitBone + ) + ); + } + ); + if (target != null && level.getWorldBorder().isWithinBounds(target.blockPosition())) { + AABB targetBounds = target.getBoundingBox(); + if (player.isWithinEntityInteractionRange(targetBounds, GlobalConfiguration.get().misc.clientInteractionLeniencyDistance.or(3.0))) { + InteractionHand hand = interactPacket.getHand(); + Vec3 location = interactPacket.getLocation(); + ItemStack tool = player.getItemInHand(hand); + if (tool.isItemEnabled(level.enabledFeatures())) { + ItemStack usedItemStack = tool.copy(); + Item itemType = tool.getItem(); + boolean triggerLeashUpdate = usedItemStack.is(Items.LEAD) && target instanceof Leashable; + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), target.getBukkitEntity(), CraftVector.toBukkit(location), CraftEquipmentSlot.getHand(hand) + ); + connection.cserver.getPluginManager().callEvent(event); + boolean resendData = event.isCancelled() || !player.getItemInHand(hand).is(itemType); + if (itemType == Items.WATER_BUCKET && target instanceof Bucketable && target instanceof LivingEntity && resendData) { + target.resendPossiblyDesyncedEntityData(player); + } + + if (resendData) { + if (MCUtil.clientPredictsInteraction(player, target, tool)) { + player.containerMenu.sendAllDataToRemote(); + } else { + player.containerMenu.forceHeldSlot(hand); + } + } + + if (triggerLeashUpdate && resendData) { + connection.send(new ClientboundSetEntityLinkPacket(target, ((Leashable)target).getLeashHolder())); + } + + if (resendData) { + target.refreshEntityData(player); + if (!(target instanceof Allay) && !(target instanceof AbstractHorse)) { + player.containerMenu.forceHeldSlot(hand); + } else { + connection.send( + new ClientboundSetEquipmentPacket( + target.getId(), + Arrays.stream(net.minecraft.world.entity.EquipmentSlot.values()) + .map(slot -> Pair.of(slot, ((LivingEntity)target).getItemBySlot(slot).copy())) + .collect(Collectors.toList()), + true + ) + ); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + return; + } + + if (player.interactOn(target, hand, location) instanceof Success success) { + ItemStack awardedForStack = success.wasItemInteraction() ? usedItemStack : ItemStack.EMPTY; + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, awardedForStack, target); + if (success.swingSource() == SwingSource.SERVER) { + player.swing(hand, true); + } + } + } + } + } else if (target == null) { + CraftEventFactory.callPlayerUseUnknownEntityEvent( + player, interactPacket.getOriginalId(), false, interactPacket.getHand(), interactPacket.getLocation() + ); + } + + if (GlobalConfiguration.get().unsupportedSettings.updateEquipmentOnPlayerActions) { + player.detectEquipmentUpdates(); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.level()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + if (connection.hasClientLoaded()) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel level = player.level(); + InteractionHand hand = packet.getHand(); + ItemStack itemStack = player.getItemInHand(hand); + player.resetLastActionTime(); + if (!itemStack.isEmpty() && itemStack.isItemEnabled(level.enabledFeatures())) { + float targetYRot = Mth.wrapDegrees(packet.getYRot()); + float targetXRot = Mth.wrapDegrees(packet.getXRot()); + if (targetXRot != player.getXRot() || targetYRot != player.getYRot()) { + player.absSnapRotationTo(targetYRot, targetXRot); + } + + Vec3 from = player.getEyePosition(); + Vec3 delta = player.getViewVector(1.0F).scale(player.blockInteractionRange()); + Vec3 to = from.add(delta); + BlockHitResult hitResult = player.level().clip(new ClipContext(from, to, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (hitResult.getType() != Type.BLOCK) { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, itemStack, hand); + cancelled = event.useItemInHand() == Result.DENY; + } else { + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(hitResult.getBlockPos()) + && player.gameMode.interactHand == hand + && ItemStack.isSameItemSameComponents(player.gameMode.interactItemStack, itemStack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + Action.RIGHT_CLICK_BLOCK, + hitResult.getBlockPos(), + hitResult.getDirection(), + itemStack, + true, + hand, + hitResult.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } + + if (cancelled) { + player.resyncUsingItem(player); + if (MCUtil.clientPredictsInteraction(player, Blocks.AIR.defaultBlockState(), itemStack)) { + player.containerMenu.sendAllDataToRemote(); + } else { + player.containerMenu.forceHeldSlotAndArmor(hand); + } + + return; + } + + itemStack = player.getItemInHand(hand); + if (itemStack.isEmpty()) { + return; + } + + InteractionResult result = player.gameMode.useItem(player, level, itemStack, hand); + afterUse.accept(result); + if (result instanceof Success success && success.swingSource() == SwingSource.SERVER) { + player.swing(hand, true); + } + } + } + } + } + } + } + + private static void callBaseEntityEvents(RelayedPacketWrapper relayedPacket, PatchedServerGamePacketListener.BaseEntityEventCallback callback) { + ModelBone hitBone = null; + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(relayedPacket.getOriginalId()); + if (activeModel == null) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(relayedPacket.getRelayedId()); + if (hitbox != null) { + hitBone = hitbox.getBone(); + activeModel = hitBone.getActiveModel(); + } + } + + if (activeModel != null) { + BaseEntity base = activeModel.getModeledEntity().getBase(); + callback.call(base, activeModel, hitBone); + } + } + + @FunctionalInterface + private interface BaseEntityEventCallback { + void call(BaseEntity var1, ActiveModel var2, ModelBone var3); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/RelayedPacketWrapper.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/RelayedPacketWrapper.java new file mode 100644 index 0000000..2342709 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/RelayedPacketWrapper.java @@ -0,0 +1,24 @@ +package com.ticxo.modelengine.v26_1.network.patch; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ServerGamePacketListener; + +public abstract class RelayedPacketWrapper> implements Packet { + private final int relayedId; + private final T original; + + protected RelayedPacketWrapper(int relayedId, T original) { + this.relayedId = relayedId; + this.original = original; + } + + abstract int getOriginalId(); + + public int getRelayedId() { + return this.relayedId; + } + + public T getOriginal() { + return this.original; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/ServerboundAttackPacketWrapper.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/ServerboundAttackPacketWrapper.java new file mode 100644 index 0000000..a283bcb --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/ServerboundAttackPacketWrapper.java @@ -0,0 +1,28 @@ +package com.ticxo.modelengine.v26_1.network.patch; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundAttackPacket; +import org.jetbrains.annotations.NotNull; + +public class ServerboundAttackPacketWrapper extends RelayedPacketWrapper { + public ServerboundAttackPacketWrapper(int relayedId, ServerboundAttackPacket original) { + super(relayedId, original); + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_ATTACK; + } + + public void handle(ServerGamePacketListener listener) { + PatchedServerGamePacketListener.handleAttack(this, listener); + } + + @Override + public int getOriginalId() { + return this.getOriginal().entityId(); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/ServerboundInteractPacketWrapper.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..d7b2792 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,49 @@ +package com.ticxo.modelengine.v26_1.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; + +public class ServerboundInteractPacketWrapper extends RelayedPacketWrapper { + public ServerboundInteractPacketWrapper(int relayedId, ServerboundInteractPacket original) { + super(relayedId, original); + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_INTERACT; + } + + public void handle(ServerGamePacketListener listener) { + PatchedServerGamePacketListener.handleInteract(this, listener); + } + + @Override + public int getOriginalId() { + return this.getOriginal().entityId(); + } + + public InteractionHand getHand() { + return this.getOriginal().hand(); + } + + public boolean isUsingSecondaryAction() { + return this.getOriginal().usingSecondaryAction(); + } + + public Vec3 getLocation() { + return this.getOriginal().location(); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.getOriginalId()) != null || tracker.getEntityRelay(this.getOriginalId()) != null; + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/BulkEntityDataEncoder.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..2d4e03b --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v26_1.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/Bundler.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/Bundler.java new file mode 100644 index 0000000..46fd6a9 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v26_1.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.getLast(); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection> packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.getLast(); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet packet : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/NetworkUtils.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/NetworkUtils.java new file mode 100644 index 0000000..d9df9ef --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/NetworkUtils.java @@ -0,0 +1,354 @@ +package com.ticxo.modelengine.v26_1.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v26_1.entity.EntityContainer; +import com.ticxo.modelengine.v26_1.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.GameProtocols.Context; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static final ProtocolInfo CLIENTBOUND_CODEC = GameProtocols.CLIENTBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + public static final ProtocolInfo SERVERBOUND_CODEC = GameProtocols.SERVERBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess()), (Context)() -> false); + private static final Map, Constructor> PACKET_CONSTRUCTOR = new HashMap<>(); + + public static RegistryFriendlyByteBuf createByteBuf() { + return new RegistryFriendlyByteBuf(Unpooled.buffer(), MinecraftServer.getServer().registryAccess()); + } + + public static RegistryFriendlyByteBuf createByteBuf(Consumer consumer) { + RegistryFriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static > T create(Class clazz, RegistryFriendlyByteBuf buf) { + Constructor constructor = PACKET_CONSTRUCTOR.computeIfAbsent(clazz, aClass -> { + try { + Constructor c = aClass.getDeclaredConstructor(RegistryFriendlyByteBuf.class); + c.setAccessible(true); + return c; + } catch (NoSuchMethodException var4x) { + try { + Constructor cx = aClass.getDeclaredConstructor(FriendlyByteBuf.class); + cx.setAccessible(true); + return cx; + } catch (NoSuchMethodException var3) { + throw new RuntimeException(var3); + } + } + }); + + try { + return (T)constructor.newInstance(buf); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException var4) { + throw new RuntimeException(var4); + } + } + + public static FriendlyByteBuf readServerbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + SERVERBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static FriendlyByteBuf readClientbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + CLIENTBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityType.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createCameraPivotSpawn(int id, UUID uuid, Vector3f pos, float height) { + ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket( + id, uuid, pos.x, pos.y - height, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createCameraPivotTeleport(int id, Vector3f pos, float height) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - height, pos.z); + ClientboundEntityPositionSyncPacket packet = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createDisplayPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - 0.375, pos.z); + ClientboundEntityPositionSyncPacket tpHigher = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + container = EntityContainer.of(id); + container.setId(id); + container.setPosRaw(pos.x, pos.y - 0.5, pos.z); + ClientboundEntityPositionSyncPacket tpLower = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Object createCameraPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos, float height) { + if (codec == null) { + return createCameraPivotTeleport(id, pos, height); + } else { + return switch (codec.update(pos.x, pos.y - height, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createCameraPivotTeleport(id, pos, height); + }; + } + } + + public static Packets.PacketSupplier createDisplayPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y, pos.z); + return playerUUID -> new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + public static Packets.PacketSupplier lodWrapper( + ModeledEntity modeledEntity, BiFunction> packetFunction + ) { + return uuid -> { + AnimationLODHandler.LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/PacketInterceptor.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..ae2c322 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/PacketInterceptor.java @@ -0,0 +1,89 @@ +package com.ticxo.modelengine.v26_1.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor

    { + private final Map>, PacketInterceptor

    .Modifier>> registry = Maps.newConcurrentMap(); + private final Map>, PacketInterceptor

    .Listener>> postRegistry = Maps.newConcurrentMap(); + + public > PacketInterceptor

    register(Class clazz, Function> function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public > PacketInterceptor

    registerPost(Class clazz, Function>> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor

    .Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection> acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor

    .Listener listener = this.postRegistry.get(original.getClass()); + return (Collection>)(listener != null ? listener.listen(original) : List.of()); + } + } + + class Listener> { + private final Class clazz; + private final Function>> function; + + public Collection> listen(Packet original) { + try { + Collection> collection = this.function.apply(this.clazz.cast(original)); + return (Collection>)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(final Class clazz, final Function>> function) { + Objects.requireNonNull(PacketInterceptor.this); + super(); + this.clazz = clazz; + this.function = function; + } + } + + class Modifier> { + private final Class clazz; + private final Function> function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(final Class clazz, final Function> function) { + Objects.requireNonNull(PacketInterceptor.this); + super(); + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/Packets.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/Packets.java new file mode 100644 index 0000000..d054a83 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v26_1.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/HeldItemParser.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..e34528c --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/HeldItemParser.java @@ -0,0 +1,186 @@ +package com.ticxo.modelengine.v26_1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v26_1.entity.EntityContainer; +import com.ticxo.modelengine.v26_1.entity.EntityUtils; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Quaternionf; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapToInt(HeldItemRenderer.Item::getId)) + )) + ); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Map items = renderer.getRendered(); + IntArrayList entityIds = IntArrayList.toList(items.values().stream().mapToInt(HeldItemRenderer.Item::getId)); + entityIds.add(renderer.getId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + return new ClientboundSetEntityDataPacket(renderer.getId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, HeldItemRenderer.Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(HeldItemRenderer.Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(11); + if (spawn) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, this.viewRange)); + } else if (renderer.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + renderer.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), spawn); + renderer.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), spawn); + renderer.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getRotation() + .ifDirty( + quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf.rotateY((float) Math.PI, new Quaternionf()))), + spawn + ); + renderer.getModel() + .ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + renderer.getDisplay() + .ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getId(), entityData); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location loc = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(loc.getX(), loc.getY(), loc.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + EntityContainer container = EntityContainer.of(renderer.getId()); + container.setPosRaw(loc.getX(), loc.getY(), loc.getZ()); + return new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getId(), renderer.getPassengers())); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/LeashParser.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/LeashParser.java new file mode 100644 index 0000000..6362ec3 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/LeashParser.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.v26_1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.v26_1.entity.EntityContainer; +import com.ticxo.modelengine.v26_1.entity.EntityUtils; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Map leashes = renderer.getRendered(); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(IntArrayList.toList(leashes.values().stream().mapMultiToInt((leash, intConsumer) -> { + intConsumer.accept(leash.getLeashId()); + intConsumer.accept(leash.getPivotId()); + })))); + } + } + + private Packets.PacketSupplier pivotSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + + private ClientboundAddEntityPacket leashSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y - 0.45, pos.z - 0.2, 0.0F, 0.0F, EntityType.BAT, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetEntityDataPacket leashData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getLeashId(), EntityUtils.DEFAULT_BAT_DATA); + } + + private ClientboundSetPassengersPacket mount(LeashRenderer.Leash renderer) { + ArrayList passengers = new ArrayList<>(1); + passengers.add(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), passengers)); + } + + private Object move(LeashRenderer.Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + } + + private ClientboundSetEntityLinkPacket link(LeashRenderer.Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(EntityContainer.of(renderer.getLeashId()), EntityContainer.of(renderer.getConnected().get())); + } + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/MountParser.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/MountParser.java new file mode 100644 index 0000000..60c8cb7 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/MountParser.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.v26_1.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_1.entity.EntityContainer; +import com.ticxo.modelengine.v26_1.entity.EntityUtils; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getMountId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Collection mounts = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(mounts.size() * 2); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getMountId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_PIVOT_DISPLAY_DATA); + } + + private ClientboundAddEntityPacket mountSpawn(MountRenderer.Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityType.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getMountId())); + } + + private ClientboundSetPassengersPacket mount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getMountId(), renderer.getPassengers())); + } + + private Packets.PacketSupplier pivotMove(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(MountRenderer.Mount renderer) { + return new Rot(renderer.getMountId(), renderer.getYaw().get(), (byte)0, false); + } + + private ClientboundSetEntityDataPacket mountHealth(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, renderer.getHealth().get()))); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(MountRenderer.Mount renderer) { + AttributeInstance attributeInstance = new AttributeInstance(Attributes.MAX_HEALTH, onDirty -> {}); + attributeInstance.setBaseValue(renderer.getMaxHealth().get().floatValue()); + return new ClientboundUpdateAttributesPacket(renderer.getMountId(), Lists.newArrayList(new AttributeInstance[]{attributeInstance})); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/NameTagParser.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..5d0876c --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/NameTagParser.java @@ -0,0 +1,184 @@ +package com.ticxo.modelengine.v26_1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.v26_1.entity.EntityContainer; +import com.ticxo.modelengine.v26_1.entity.EntityUtils; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTagRenderer.NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTagRenderer.NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Collection nameTags = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(nameTags.size() * 2); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + return !spawn ? null : new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTagRenderer.NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(7); + renderer.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + renderer.getTranslate().ifDirty(flag -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getScale().ifDirty(flag -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getTextOpacity().ifDirty(flag -> entityData.add(new DataValue(26, EntityDataSerializers.BYTE, flag)), spawn); + renderer.getBackgroundColor().ifDirty(flag -> entityData.add(new DataValue(25, EntityDataSerializers.INT, flag)), spawn); + renderer.getLineWidth().ifDirty(flag -> entityData.add(new DataValue(24, EntityDataSerializers.INT, flag)), spawn); + renderer.getStyle().ifDirty(flags -> entityData.add(new DataValue(27, EntityDataSerializers.BYTE, flags)), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new MatchException(null, null); + }; + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, value)); + }, spawn); + renderer.getJsonString() + .ifDirty( + jsonString -> { + if (jsonString == null) { + entityData.add(new DataValue(23, EntityDataSerializers.COMPONENT, Component.empty())); + } else { + entityData.add( + new DataValue(23, EntityDataSerializers.COMPONENT, Optional.ofNullable(CraftChatMessage.fromJSON(jsonString)).orElse(Component.empty())) + ); + } + }, + spawn + ); + renderer.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getTagId(), entityData); + } + } + + private Object pivotMove(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTagRenderer.NameTag renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getTagId())); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/SegmentParser.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..554d86d --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/SegmentParser.java @@ -0,0 +1,205 @@ +package com.ticxo.modelengine.v26_1.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_1.entity.EntityContainer; +import com.ticxo.modelengine.v26_1.entity.EntityUtils; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + this.viewRange = renderer.getActiveModel().getViewRange(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (SegmentRenderer.Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + IntArrayList destroy = new IntArrayList(); + + for (SegmentRenderer.Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(destroy))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(SegmentRenderer.Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SegmentRenderer.Pivot pivot) { + return new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(SegmentRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(SegmentRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(SegmentRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + ArrayList> entityData = new ArrayList<>(13); + if (force) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } else if (bone.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : 1)), force); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), force); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/SubHitboxParser.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..b6bcc76 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/behavior/SubHitboxParser.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v26_1.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.v26_1.entity.EntityContainer; +import com.ticxo.modelengine.v26_1.entity.EntityUtils; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitboxRenderer.SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Collection subHitboxes = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(subHitboxes.size() * 2); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private Object pivotMove(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getHitboxId())); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitboxRenderer.SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitboxRenderer.SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(4); + renderer.getWidth().ifDirty(width -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, width)), spawn); + renderer.getHeight().ifDirty(height -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, height)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getHitboxId(), entityData); + } + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/model/DisplayParser.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/model/DisplayParser.java new file mode 100644 index 0000000..57c820b --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/model/DisplayParser.java @@ -0,0 +1,791 @@ +package com.ticxo.modelengine.v26_1.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_1.entity.EntityContainer; +import com.ticxo.modelengine.v26_1.entity.EntityUtils; +import com.ticxo.modelengine.v26_1.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_1.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static StreamCodec CUSTOM_PAYLOAD_CODEC; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + if (renderer.hasGlowAudience()) { + this.updateAudienceGlow(renderer, data.getTracking().keySet(), data.getStartTracking(), this.noCullForcePlayers); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + private void updateAudienceGlow(DisplayRenderer renderer, Set current, Set startTracking, Set forceUpdates) { + for (DisplayBone bone : renderer.getRendered().values()) { + Set audience = bone.getGlowAudience().get(); + if (audience != null) { + boolean changed = bone.isAudienceGlowDirty(); + if (changed || !startTracking.isEmpty() || !forceUpdates.isEmpty()) { + boolean glowing = bone.getAudienceGlowing().get(); + int color = bone.getAudienceGlowColor().get(); + Set on = new HashSet<>(); + Set off = new HashSet<>(); + if (changed) { + for (UUID uuid : current) { + if (glowing && audience.contains(uuid)) { + on.add(uuid); + } else { + off.add(uuid); + } + } + + bone.clearAudienceGlowDirty(); + } else if (glowing) { + for (UUID uuidx : startTracking) { + if (audience.contains(uuidx)) { + on.add(uuidx); + } + } + + for (UUID uuidxx : forceUpdates) { + if (audience.contains(uuidxx)) { + on.add(uuidxx); + } + } + } + + if (!on.isEmpty() || !off.isEmpty()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + int id = boneData.getId(); + if (!on.isEmpty()) { + NetworkUtils.send(on, this.audienceGlowData(id, true, color)); + } + + if (!off.isEmpty()) { + NetworkUtils.send(off, this.audienceGlowData(id, false, color)); + } + } + } + } + } + } + } + + private ClientboundSetEntityDataPacket audienceGlowData(int entityId, boolean glowing, int color) { + ArrayList> entityData = new ArrayList<>(2); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(glowing ? 96 : 32))); + if (glowing) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + + return new ClientboundSetEntityDataPacket(entityId, entityData); + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + set.add((Packet)this.pivotCameraResize(pivot)); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(destroy)))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(hitboxDestroy)))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)(u -> this.displayData(u, null, boneData, false, transformOnly))); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + AnimationLODHandler.LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + RegistryFriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(RegistryFriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CODEC == null) { + Field field = ClientboundCustomPayloadPacket.class.getField("GAMEPLAY_STREAM_CODEC"); + field.setAccessible(true); + CUSTOM_PAYLOAD_CODEC = (StreamCodec)field.get(null); + } + + return (Packet)CUSTOM_PAYLOAD_CODEC.decode(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData( + BulkEntityDataEncoder encoder, + UUID uuid, + @Nullable AnimationLODHandler.LODTracker tracker, + DisplayBone.BoneData boneData, + boolean force, + boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + + for (DisplayBone bone : new ArrayList<>(renderer.getRendered().values())) { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + } + + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? new ClientboundSetEntityDataPacket(pivot.getId(), this.cameraPivotData(pivot.getCameraHeight().get())) + : new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private List> cameraPivotData(float height) { + return List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(8, EntityDataSerializers.FLOAT, 0.0F), + new DataValue(9, EntityDataSerializers.FLOAT, height) + ); + } + + private ClientboundSetPassengersPacket pivotMount(DisplayRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(DisplayRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundSetEntityDataPacket pivotCameraResize(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() && pivot.getCameraHeight().isDirty() + ? new ClientboundSetEntityDataPacket(pivot.getId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, pivot.getCameraHeight().get()))) + : null; + } + + private ClientboundAddEntityPacket displaySpawn(DisplayRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData( + UUID uuid, @Nullable AnimationLODHandler.LODTracker tracker, DisplayBone.BoneData boneData, boolean force, boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + ArrayList> entityData = new ArrayList<>(13); + if (!force && update != 0) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : lodTick)), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + entityData.add(new DataValue(16, EntityDataSerializers.INT, val)); + } + }, force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + } + }, force); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + + private ClientboundSetEntityDataPacket displayVisibleData(DisplayBone.BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)))); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color))); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val))); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F))); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)))); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()))); + this.cleanupQueue.add(bone::clearDirty); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(DisplayRenderer.Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(DisplayRenderer.Hitbox hitbox) { + return !hitbox.isPivotVisible() ? null : new ClientboundSetEntityDataPacket(hitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket hitboxSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(4); + hitbox.getWidth().ifDirty(val -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, val)), spawn); + hitbox.getHeight().ifDirty(val -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getHitboxId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(2); + hitbox.getShadowRadius().ifDirty(val -> entityData.add(new DataValue(18, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getShadowId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(DisplayRenderer.Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(DisplayRenderer.Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + return new ClientboundSetPassengersPacket(EntityContainer.of(hitbox.getPivotId(), passengers)); + } + } +} diff --git a/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/vfx/VFXDisplayParser.java b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..3429f45 --- /dev/null +++ b/nms/v26_1/src/main/java/com/ticxo/modelengine/v26_1/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,124 @@ +package com.ticxo.modelengine.v26_1.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v26_1.entity.EntityContainer; +import com.ticxo.modelengine.v26_1.entity.EntityUtils; +import com.ticxo.modelengine.v26_1.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_1.network.utils.Packets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(new int[]{vfx.getPivotId(), vfx.getModelId()})); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXDisplayRenderer.VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetEntityDataPacket(vfx.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXDisplayRenderer.VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityType.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXDisplayRenderer.VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(9); + if (spawn) { + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)32)); + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, 4096.0F)); + entityData.add(new DataValue(24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal())); + } else if (vfx.isModelDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + vfx.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + vfx.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + vfx.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + vfx.clearModelDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(vfx.getModelId(), entityData); + } + } + + private Object teleport(VFXDisplayRenderer.VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetPassengersPacket(EntityContainer.of(vfx.getPivotId(), vfx.getModelId())); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSFields.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSFields.java new file mode 100644 index 0000000..e46ece5 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSFields.java @@ -0,0 +1,56 @@ +package com.ticxo.modelengine.v26_2; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionUtils.ReflectionEnum { + ENTITY_dimensions(Entity.class, "dimensions", "dimensions"), + ENTITY_eyeHeight(Entity.class, "eyeHeight", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "noJumpDelay", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "jumping", "jumping"), + MOB_lookControl(Mob.class, "lookControl", "lookControl"), + MOB_moveControl(Mob.class, "moveControl", "moveControl"), + MOB_navigation(Mob.class, "navigation", "navigation"), + MOB_goalSelector(Mob.class, "goalSelector", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "bodyRotationControl", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "clientIsFloating", "clientIsFloating"), + MOVE_CONTROL_operation(MoveControl.class, "operation", "operation"), + TRACKED_ENTITY_range(TrackedEntity.class, "range", "range"), + LEVEL_soundSeedGenerator(Level.class, "soundSeedGenerator", "soundSeedGenerator"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "entityId", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "entityId", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(final Class target, final String obfuscated, final String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSHandler_v26_2.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSHandler_v26_2.java new file mode 100644 index 0000000..a7be46d --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSHandler_v26_2.java @@ -0,0 +1,225 @@ +package com.ticxo.modelengine.v26_2; + +import com.mojang.math.MatrixUtil; +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.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v26_2.entity.EntityContainer; +import com.ticxo.modelengine.v26_2.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v26_2.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_2.parser.behavior.LeashParser; +import com.ticxo.modelengine.v26_2.parser.behavior.MountParser; +import com.ticxo.modelengine.v26_2.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v26_2.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v26_2.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v26_2.parser.model.DisplayParser; +import com.ticxo.modelengine.v26_2.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.components.CustomModelDataComponent; +import org.bukkit.util.Transformation; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class NMSHandler_v26_2 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + private boolean manualTranslucencyOrder; + private boolean forceCMD; + + public NMSHandler_v26_2() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + public void updateConfig() { + this.manualTranslucencyOrder = ConfigProperty.MANUAL_TRANSLUCENCY_ORDER.getBoolean(); + this.forceCMD = ConfigProperty.FORCE_CMD.getBoolean(); + } + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + RegistryFriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, NetworkUtils.create(ClientboundSetPassengersPacket.class, byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public Set createStack(ItemModelData data, ItemModelData.Context context) { + if (this.forceCMD) { + return NMSHandler.super.createStack(data, context); + } else { + ItemStack item = new ItemStack(this.manualTranslucencyOrder && !data.isTranslucent() ? Material.GLASS : Material.BONE); + item.editMeta(itemMeta -> { + itemMeta.setItemModel(data.getSingleComposite().model()); + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(context.color())); + if (data.getVariant() != null) { + cmdComp.setStrings(List.of(data.getVariant())); + } + + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return Set.of(item); + } + } + + @Override + public boolean colorStack(ItemStack stack, Color color) { + stack.editMeta(itemMeta -> { + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(color)); + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return true; + } + + @Override + public void applyPlayerHeadItemModel(ItemStack stack) { + stack.editMeta(meta -> meta.setItemModel(this.getPlayerHeadModelKey())); + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(EntityContainer.of(mountId, passengerIds)); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + Vector3f translation = new Vector3f(); + Quaternionf leftRotation = new Quaternionf(); + Vector3f scale = new Vector3f(); + Quaternionf rightRotation = new Quaternionf(); + MatrixUtil.svdDecompose(transform, translation, leftRotation, scale, rightRotation); + return new Transformation(translation, leftRotation, scale, rightRotation); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSMethods.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSMethods.java new file mode 100644 index 0000000..92c3c02 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/NMSMethods.java @@ -0,0 +1,48 @@ +package com.ticxo.modelengine.v26_2; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements ReflectionUtils.MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "a", "getInstrument", ItemStack.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityContainer.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityContainer.java new file mode 100644 index 0000000..63faf34 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityContainer.java @@ -0,0 +1,60 @@ +package com.ticxo.modelengine.v26_2.entity; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.network.syncher.SynchedEntityData.Builder; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.ApiStatus.Internal; + +@Internal +public class EntityContainer extends Entity { + public static EntityContainer of(int id) { + return new EntityContainer(id); + } + + public static Entity of(int id, int... passengerIds) { + EntityContainer container = of(id); + container.setPassengers(Arrays.stream(passengerIds).mapToObj(EntityContainer::new).toList()); + return container; + } + + public static Entity of(int id, Collection passengerIds) { + EntityContainer container = of(id); + container.setPassengers(passengerIds.stream().map(EntityContainer::new).toList()); + return container; + } + + private EntityContainer(int id) { + super(EntityTypes.INTERACTION, MinecraftServer.getServer().overworld()); + this.setId(id); + this.setPosRaw(0.0, 0.0, 0.0); + this.setRot(0.0F, 0.0F); + this.setOnGround(false); + } + + protected void setPassengers(List passengers) { + this.passengers = ImmutableList.copyOf(passengers); + } + + protected void defineSynchedData(@NotNull Builder builder) { + } + + public boolean hurtServer(ServerLevel world, DamageSource source, float amount) { + return false; + } + + protected void readAdditionalSaveData(ValueInput valueInput) { + } + + protected void addAdditionalSaveData(ValueOutput valueOutput) { + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityHandlerImpl.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..6758f31 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityHandlerImpl.java @@ -0,0 +1,845 @@ +package com.ticxo.modelengine.v26_2.entity; + +import ca.spottedleaf.moonrise.patches.entity_tracker.EntityTrackerEntity; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v26_2.NMSFields; +import com.ticxo.modelengine.v26_2.NMSMethods; +import com.ticxo.modelengine.v26_2.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v26_2.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v26_2.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v26_2.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v26_2.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v26_2.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v26_2.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v26_2.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v26_2.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v26_2.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_2.network.utils.Packets; +import io.papermc.paper.adventure.PaperAdventure; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.kyori.adventure.text.Component; +import net.minecraft.core.Holder; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult.Fail; +import net.minecraft.world.InteractionResult.Pass; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.TryEmptyHandInteraction; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityAttachments; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemUseAnimation; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.World; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(MinecraftServer.getServer().overworld().getWorld()); + } + + @Override + public int getEntityId(Entity entity) { + return EntityUtils.nms(entity).getId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + float width = (float)hitbox.getMaxWidth(); + float height = (float)hitbox.getHeight(); + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions(width, height, (float)hitbox.getEyeHeight(), EntityAttachments.createDefault(width, height), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + if (EntityUtils.nms(entity) instanceof LivingEntity living) { + living.getAttributes().registerAttribute(Attributes.STEP_HEIGHT); + Objects.requireNonNull(living.getAttribute(Attributes.STEP_HEIGHT)).setBaseValue(height); + } + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityTypes.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y - nmsEntity.getVehicleAttachmentPoint(this.dummyArmorStand).y; + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + this.getEntityId(entity), List.of(new DataValue(0, EntityDataSerializers.BYTE, data)) + ); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + switch (oldNav) { + case WallClimberNavigation wallClimberNavigation: + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + break; + case GroundPathNavigation groundPathNavigation: + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + break; + case FlyingPathNavigation flyingPathNavigation: + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + break; + case WaterBoundPathNavigation waterBoundPathNavigation: + newNav = new WaterBoundNavigationWrapper(mob); + break; + case AmphibiousPathNavigation amphibiousPathNavigation: + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + break; + default: + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var13) { + var13.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + World bukkitWorld = location.getWorld(); + if (bukkitWorld == null) { + if (bone.getActiveModel().getModeledEntity().getBase().getOriginal() instanceof Entity entity) { + bukkitWorld = entity.getWorld(); + } + + if (bukkitWorld == null) { + return null; + } + } + + ServerLevel level = ((CraftWorld)bukkitWorld).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + if (!entity.isRemoved() && entity.isValid()) { + int attempts = 0; + + while (level.getEntity(entity.getUUID()) != null && attempts++ < 8) { + entity.setUUID(UUID.randomUUID()); + } + + if (level.getEntity(entity.getUUID()) != null) { + entity.discard(); + } else { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + } + } + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity.level() instanceof ServerLevel worldserver) { + return nmsEntity.hurtServer(worldserver, damageSource, amount); + } + } + + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + + @Override + public EntityHandler.InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, Vec3.ZERO + ); + + return switch (result) { + case Success success -> success.equals(net.minecraft.world.InteractionResult.SUCCESS_SERVER) + ? EntityHandler.InteractionResult.SUCCESS + : ( + success.equals(net.minecraft.world.InteractionResult.SUCCESS) + ? EntityHandler.InteractionResult.CONSUME_PARTIAL + : EntityHandler.InteractionResult.CONSUME + ); + case TryEmptyHandInteraction ignored -> EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED; + case Pass ignoredx -> EntityHandler.InteractionResult.PASS; + case Fail ignoredxx -> EntityHandler.InteractionResult.FAIL; + default -> throw new MatchException(null, null); + }; + } else { + return EntityHandler.InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket( + DynamicHitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA + ); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityTypes.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(DynamicHitbox.getHitboxId(), EntityUtils.DEFAULT_SLIME_DATA); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket( + EntityContainer.of(DynamicHitbox.getPivotId(), DynamicHitbox.getHitboxId()) + ); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + Objects.requireNonNull(EntityHandlerImpl.this); + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, 0, nmsPlayer.getYRot(), nmsPlayer.getXRot() + ); + useItemPacket.timestamp = System.currentTimeMillis(); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != ItemUseAnimation.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + player.getEntityId(), List.of(new DataValue(8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3))) + ); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call(instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_soundSeedGenerator); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityTypes.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public Float getCameraEyeHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return nmsEntity.getDimensions(Pose.STANDING).eyeHeight(); + } + + @Override + public Float getCameraPivotHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + EntityDimensions dimensions = nmsEntity.getDimensions(nmsEntity.getPose()); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityTypes.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 attachment = ReflectionUtils.call(nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, dimensions, 1.0F); + return attachment == null ? null : (float)(dimensions.eyeHeight() - attachment.y); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public Set getCollidableExemptions(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity living ? living.collidableExemptions : null; + } + + @Override + public Component getCustomName(Entity entity) { + net.minecraft.network.chat.Component name = EntityUtils.nms(entity).getCustomName(); + return name == null ? null : PaperAdventure.asAdventure(name); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + private static Int2ObjectMap getEntityMap(ChunkMap chunkMap) { + return chunkMap.entityMap; + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + if (!ServerInfo.IS_FOLIA && !ServerInfo.IS_PAPER) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = getEntityMap(level.getChunkSource().chunkMap); + if (map == null) { + return new TempTrackedEntity(entity); + } else { + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = getEntityMap(lvl.getChunkSource().chunkMap); + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + } else { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity instanceof EntityTrackerEntity) { + TrackedEntity tracker = nmsEntity.moonrise$getTrackedEntity(); + if (tracker != null) { + return new TrackedEntityImpl(entity, () -> { + net.minecraft.world.entity.Entity current = EntityUtils.nms(entity); + return current instanceof EntityTrackerEntity ? current.moonrise$getTrackedEntity() : null; + }, tracker); + } + } + + return new TempTrackedEntity(entity); + } + } + + @Override + public boolean isGlowing(Entity entity) { + return EntityUtils.nms(entity).getSharedFlag(6); + } + + @Override + public boolean isVisualFire(Entity entity) { + return EntityUtils.nms(entity).getSharedFlag(0); + } + + @Override + public int getFireTicks(Entity entity) { + return this.isVisualFire(entity) ? 1 : 0; + } + + @Override + public BoundingBox getBoundingBox(Entity entity) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + return new BoundingBox(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public void getLocation(Entity entity, Location location) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + Vec3 pos = nms.position(); + location.setWorld(nms.level().getWorld()); + location.setX(pos.x); + location.setY(pos.y); + location.setZ(pos.z); + location.setYaw(nms.getYRot()); + location.setPitch(nms.getXRot()); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + EntityHandler.BoxRelToCam relX = EntityHandler.BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + EntityHandler.BoxRelToCam relY = EntityHandler.BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + EntityHandler.BoxRelToCam relZ = EntityHandler.BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == EntityHandler.BoxRelToCam.INSIDE && relY == EntityHandler.BoxRelToCam.INSIDE && relZ == EntityHandler.BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.DUST, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (ServerInfo.IS_FOLIA && !Bukkit.isPrimaryThread()) { + return true; + } else if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityMetadataID.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityMetadataID.java new file mode 100644 index 0000000..99d1c05 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityMetadataID.java @@ -0,0 +1,37 @@ +package com.ticxo.modelengine.v26_2.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_POS_ROT_DURATION = 10; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 18; +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityUtils.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityUtils.java new file mode 100644 index 0000000..ff54e69 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/EntityUtils.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.v26_2.entity; + +import java.util.List; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.entity.CraftEntity; + +public class EntityUtils { + public static final List> DEFAULT_AREA_EFFECT_CLOUD_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(8, EntityDataSerializers.FLOAT, 0.0F) + ); + public static final List> DEFAULT_PIVOT_DISPLAY_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(10, EntityDataSerializers.INT, 1) + ); + public static final List> DEFAULT_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(18, EntityDataSerializers.INT, 2) + ); + public static final List> DEFAULT_BAT_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE) + ); + public static final List> DEFAULT_ARMOR_STAND_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(15, EntityDataSerializers.BYTE, (byte)16) + ); + + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/OcclusionClipContext.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/OcclusionClipContext.java new file mode 100644 index 0000000..fa6e74e --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v26_2.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape() == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (!(tX <= 1.0) && !(tY <= 1.0) && !(tZ <= 1.0)) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/TrackedEntityImpl.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..bc5e435 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/TrackedEntityImpl.java @@ -0,0 +1,333 @@ +package com.ticxo.modelengine.v26_2.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v26_2.NMSFields; +import com.ticxo.modelengine.v26_2.NMSMethods; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + Set tracked = this.entity.getTrackedPlayers(); + HashSet set = new HashSet<>(Math.max(8, (int)((tracked.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (Player player : tracked) { + if (this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null && this.playerPredicate.test(playerx) && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + set.add(playerx.getUniqueId()); + } + } + + return set; + } + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + Set tracked = this.entity.getTrackedPlayers(); + HashSet set = new HashSet<>(Math.max(8, (int)((tracked.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (Player player : tracked) { + if (predicate.test(player) && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null + && predicate.test(playerx) + && this.playerPredicate.test(playerx) + && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + set.add(playerx.getUniqueId()); + } + } + + return set; + } + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (Player player : this.entity.getTrackedPlayers()) { + if (predicate.test(player) && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null + && predicate.test(playerx) + && this.playerPredicate.test(playerx) + && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + dest.add(playerx.getUniqueId()); + } + } + + return dest; + } + } + + @Override + public boolean isViewerSetUnchanged() { + if (ServerInfo.IS_FOLIA + || this.mayHaveForced && (!this.forcedPairing.isEmpty() || !this.forcedRemove.isEmpty()) + || this.playerPredicate != DEFAULT_PREDICATE) { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } else if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/BodyRotationControlWrapper.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..6df1134 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v26_2.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/LookControlWrapper.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..078aef3 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/LookControlWrapper.java @@ -0,0 +1,152 @@ +package com.ticxo.modelengine.v26_2.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import io.papermc.paper.entity.activation.ActivationRange; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + private MovementOverride movementOverride; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateDirection(this, this.modeledEntity); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + if (this.isActive()) { + this.original.tick(); + } + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + private boolean isActive() { + return ActivationRange.checkIfActive(this.mob); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/MoveControlWrapper.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..480edb9 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/controller/MoveControlWrapper.java @@ -0,0 +1,272 @@ +package com.ticxo.modelengine.v26_2.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_2.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.Input; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + protected MovementOverride movementOverride; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateMovement(this, modeledEntity); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + if (entity instanceof Player player) { + Input playerInput = player.getCurrentInput(); + controller.setInput( + new MountController.MountInput( + playerInput.isForward(), + playerInput.isBackward(), + playerInput.isLeft(), + playerInput.isRight(), + playerInput.isJump(), + playerInput.isSneak(), + playerInput.isSprint() + ) + ); + } else { + controller.setInput(new MountController.MountInput()); + } + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/hitbox/HitboxEntityImpl.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..5a1f810 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,288 @@ +package com.ticxo.modelengine.v26_2.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v26_2.NMSFields; +import com.ticxo.modelengine.v26_2.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; +import org.jspecify.annotations.NonNull; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityTypes.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + public boolean canBeHitByProjectile() { + return this.subHitbox.isCanBeHitByProjectile(); + } + + @NotNull + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public boolean isInvisible() { + return true; + } + + public void push(@NotNull Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox(Vec3 position) { + if (this.subHitbox == null) { + return super.makeBoundingBox(position); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(@NotNull Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurtServer(@NotNull ServerLevel world, @NotNull DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurtServer(world, source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + BaseEntity baseEntity = this.bone.getActiveModel().getModeledEntity().getBase(); + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return baseEntity.hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, @NotNull InteractionHand hand, @NonNull Vec3 location) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, entity, new Vector(0, 0, 0), hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand, location); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact(this, player.getBukkitEntity(), hand == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND); + + return (InteractionResult)(switch (result) { + case SUCCESS -> InteractionResult.SUCCESS_SERVER; + case SUCCESS_NO_ITEM_USED -> InteractionResult.TRY_WITH_EMPTY_HAND; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.SUCCESS; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }); + } + } + + public boolean shouldBeSaved() { + return false; + } + + @NotNull + public CraftEntity getBukkitEntity() { + CraftEntity bukkitEntity = this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + CraftEntity var5 = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(var5); + return var5; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(@NotNull RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + if (!this.markRemoved) { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + + try { + Promise.start(this.getBukkitEntity()).thenRunSync(() -> { + if (!this.isRemoved()) { + this.discard(); + } + }); + } catch (Throwable var2) { + } + } + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/hitbox/OBB.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/hitbox/OBB.java new file mode 100644 index 0000000..a22e55f --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v26_2.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..15cdc53 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v26_2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/FlyingNavigationWrapper.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..c8715f2 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v26_2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/GroundNavigationWrapper.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..99be282 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v26_2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/WallClimberNavigationWrapper.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..3fe2bfe --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v26_2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..fb22569 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v26_2.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/ModelEngineChannelHandler.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..6c75d41 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/ModelEngineChannelHandler.java @@ -0,0 +1,474 @@ +package com.ticxo.modelengine.v26_2.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_2.NMSFields; +import com.ticxo.modelengine.v26_2.entity.EntityContainer; +import com.ticxo.modelengine.v26_2.network.patch.ServerboundAttackPacketWrapper; +import com.ticxo.modelengine.v26_2.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_2.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntList; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundAttackPacket; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundEntityPositionSyncPacket.class, this::handlePositionSync) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundAttackPacket.class, this::handleAttack) + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove) + .register(ServerboundClientTickEndPacket.class, this::handleClientTickEnd); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet rawPacket && asClientPacket(rawPacket) instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + Collection> post = this.writeInterceptors.acceptPost(result); + if (!post.isEmpty()) { + list.addAll(post); + } + } + } + + if (!list.isEmpty()) { + Packet var12 = new ClientboundBundlePacket(list); + super.write(ctx, var12, promise); + } + } else { + Packet var13 = this.writeInterceptors.accept(packet); + if (var13 == null) { + return; + } + + Collection> post = this.writeInterceptors.acceptPost(var13); + if (post.isEmpty()) { + super.write(ctx, var13, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var13); + list.addAll(post); + Packet var14 = new ClientboundBundlePacket(list); + super.write(ctx, var14, promise); + } + } + } catch (Throwable var11) { + var11.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List> handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List> handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + List> list = null; + Optional maybeMount = model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT); + if (maybeMount.isPresent() && maybeMount.get() instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + MountRenderer.Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + if (mount == null) { + return null; + } + + CollectionDataTracker ids = mount.getPassengers(); + list = new ArrayList<>(); + list.add(new ClientboundSetPassengersPacket(EntityContainer.of(mount.getMountId(), ids))); + } + } + + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + IntList ids = packet.getEntityIds(); + + for (int i = 0; i < ids.size(); i++) { + this.markViewersDirty(ids.getInt(i)); + } + + int[] set = packet.getEntityIds().intStream().filter(id -> ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE).toArray(); + return set.length == packet.getEntityIds().size() ? packet : new ClientboundRemoveEntitiesPacket(IntArrayList.wrap(set)); + } + + private > T handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readClientbound(packet); + + Packet var4; + try { + int id = buf.readVarInt(); + var4 = ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } finally { + buf.release(); + } + + return (T)var4; + } + + private > T handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundEntityPositionSyncPacket handlePositionSync(ClientboundEntityPositionSyncPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + int id = packet.entityId(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + return !changed ? packet : new ClientboundSetPassengersPacket(EntityContainer.of(packet.getVehicle(), new IntArrayList(merged))); + } + } + } + + private Packet handleAttack(ServerboundAttackPacket packet) { + int entityId = packet.entityId(); + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundAttackPacketWrapper(hitbox.getTarget(), packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundAttackPacketWrapper(id, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundAttackPacketWrapper(relayed, packet) : packet); + } + } + + private Packet handleInteract(ServerboundInteractPacket packet) { + int entityId = packet.entityId(); + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(hitbox.getTarget(), packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(id, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundInteractPacketWrapper(relayed, packet) : packet); + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountController.MountInput input = controller.getInput(); + if (input == null) { + controller.setInput( + new MountController.MountInput( + inputPacket.input().forward(), + inputPacket.input().backward(), + inputPacket.input().left(), + inputPacket.input().right(), + inputPacket.input().jump(), + inputPacket.input().shift(), + inputPacket.input().sprint() + ) + ); + } else { + input.setForward(inputPacket.input().forward()); + input.setBackward(inputPacket.input().backward()); + input.setLeft(inputPacket.input().left()); + input.setRight(inputPacket.input().right()); + input.setJump(inputPacket.input().jump()); + input.setSneak(inputPacket.input().shift()); + input.setSprint(inputPacket.input().sprint()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + if (!ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + private ServerboundClientTickEndPacket handleClientTickEnd(ServerboundClientTickEndPacket packet) { + if (ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + @SuppressWarnings("unchecked") + private static Packet asClientPacket(Object packet) { + return (Packet)packet; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/NetworkHandlerImpl.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..2bca996 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/NetworkHandlerImpl.java @@ -0,0 +1,139 @@ +package com.ticxo.modelengine.v26_2.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.v26_2.network.utils.Bundler; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = listener.connection; + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = listener.connection; + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection> collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/PatchedServerGamePacketListener.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..65d8a77 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,389 @@ +package com.ticxo.modelengine.v26_2.network.patch; + +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v26_2.NMSMethods; +import io.papermc.paper.configuration.GlobalConfiguration; +import io.papermc.paper.util.MCUtil; +import java.util.Arrays; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import net.minecraft.advancements.triggers.CriteriaTriggers; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.SwingSource; +import net.minecraft.world.entity.Bucketable; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.Leashable; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.animal.equine.AbstractHorse; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.projectile.arrow.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.CraftEquipmentSlot; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.event.Event.Result; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerKickEvent.Cause; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleAttack(ServerboundAttackPacketWrapper attackPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(attackPacket, connection, connection.getPlayer().level()); + ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + if (connection.hasClientLoaded()) { + CraftPlayer craftPlayer = player.getBukkitEntity(); + ServerLevel level = player.level(); + CraftServer craftServer = level.getServer().server; + Entity target = level.getEntityOrPart(attackPacket.getRelayedId()); + if (target != player || player.isSpectator()) { + player.resetLastActionTime(); + callBaseEntityEvents( + attackPacket, + (base, model, hitBone) -> craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.ATTACK, + EquipmentSlot.HAND, + player.isShiftKeyDown(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null, + hitBone + ) + ) + ); + if (target != null && level.getWorldBorder().isWithinBounds(target.blockPosition())) { + AABB targetBounds = target.getBoundingBox(); + ItemStack mainHandItem = player.getMainHandItem(); + if (player.isWithinAttackRange(mainHandItem, targetBounds, GlobalConfiguration.get().misc.clientInteractionLeniencyDistance.or(3.0)) + && !mainHandItem.has(DataComponents.PIERCING_WEAPON)) { + if (target instanceof ItemEntity + || target instanceof ExperienceOrb + || target == player + || target instanceof AbstractArrow abstractArrow && !abstractArrow.isAttackable()) { + connection.disconnect(Component.translatable("multiplayer.disconnect.invalid_entity_attacked"), Cause.INVALID_ENTITY_ATTACKED); + LOGGER.warn("Player {} tried to attack an invalid entity", player.getPlainTextName()); + } else if (mainHandItem.isItemEnabled(level.enabledFeatures()) && !player.cannotAttackWithItem(mainHandItem, 5)) { + player.attack(target); + } + } + } else if (target == null) { + CraftEventFactory.callPlayerUseUnknownEntityEvent(player, attackPacket.getOriginalId(), true, InteractionHand.MAIN_HAND, null); + } + + if (GlobalConfiguration.get().unsupportedSettings.updateEquipmentOnPlayerActions) { + player.detectEquipmentUpdates(); + } + } + } + } + } + } + + public static void handleInteract(ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().level()); + ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + if (connection.hasClientLoaded()) { + CraftPlayer craftPlayer = player.getBukkitEntity(); + ServerLevel level = player.level(); + CraftServer craftServer = level.getServer().server; + Entity target = level.getEntityOrPart(interactPacket.getRelayedId()); + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.OFF_HAND); + } + + if (target != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + callBaseEntityEvents( + interactPacket, + (base, model, hitBone) -> { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null, + hitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + null, + hitBone + ) + ); + Vec3 pos = interactPacket.getLocation(); + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT_ON, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + position, + hitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT_ON, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + position, + hitBone + ) + ); + } + ); + if (target != null && level.getWorldBorder().isWithinBounds(target.blockPosition())) { + AABB targetBounds = target.getBoundingBox(); + if (player.isWithinEntityInteractionRange(targetBounds, GlobalConfiguration.get().misc.clientInteractionLeniencyDistance.or(3.0))) { + InteractionHand hand = interactPacket.getHand(); + Vec3 location = interactPacket.getLocation(); + ItemStack tool = player.getItemInHand(hand); + if (tool.isItemEnabled(level.enabledFeatures())) { + ItemStack usedItemStack = tool.copy(); + Item itemType = tool.getItem(); + boolean triggerLeashUpdate = usedItemStack.is(Items.LEAD) && target instanceof Leashable; + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), target.getBukkitEntity(), CraftVector.toBukkit(location), CraftEquipmentSlot.getHand(hand) + ); + connection.cserver.getPluginManager().callEvent(event); + boolean resendData = event.isCancelled() || !player.getItemInHand(hand).is(itemType); + if (itemType == Items.WATER_BUCKET && target instanceof Bucketable && target instanceof LivingEntity && resendData) { + target.resendPossiblyDesyncedEntityData(player); + } + + if (resendData) { + if (MCUtil.clientPredictsInteraction(player, target, tool)) { + player.containerMenu.sendAllDataToRemote(); + } else { + player.containerMenu.forceHeldSlot(hand); + } + } + + if (triggerLeashUpdate && resendData) { + connection.send(new ClientboundSetEntityLinkPacket(target, ((Leashable)target).getLeashHolder())); + } + + if (resendData) { + target.refreshEntityData(player); + if (!(target instanceof Allay) && !(target instanceof AbstractHorse)) { + player.containerMenu.forceHeldSlot(hand); + } else { + connection.send( + new ClientboundSetEquipmentPacket( + target.getId(), + Arrays.stream(net.minecraft.world.entity.EquipmentSlot.values()) + .map(slot -> Pair.of(slot, ((LivingEntity)target).getItemBySlot(slot).copy())) + .collect(Collectors.toList()), + true + ) + ); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + return; + } + + if (player.interactOn(target, hand, location) instanceof Success success) { + ItemStack awardedForStack = success.wasItemInteraction() ? usedItemStack : ItemStack.EMPTY; + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, awardedForStack, target); + if (success.swingSource() == SwingSource.SERVER) { + player.swing(hand, true); + } + } + } + } + } else if (target == null) { + CraftEventFactory.callPlayerUseUnknownEntityEvent( + player, interactPacket.getOriginalId(), false, interactPacket.getHand(), interactPacket.getLocation() + ); + } + + if (GlobalConfiguration.get().unsupportedSettings.updateEquipmentOnPlayerActions) { + player.detectEquipmentUpdates(); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.level()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp)); + if (shouldLimit) { + if (connection.hasClientLoaded()) { + connection.ackBlockChangesUpTo(packet.getSequence()); + ServerLevel level = player.level(); + InteractionHand hand = packet.getHand(); + ItemStack itemStack = player.getItemInHand(hand); + player.resetLastActionTime(); + if (!itemStack.isEmpty() && itemStack.isItemEnabled(level.enabledFeatures())) { + float targetYRot = Mth.wrapDegrees(packet.getYRot()); + float targetXRot = Mth.wrapDegrees(packet.getXRot()); + if (targetXRot != player.getXRot() || targetYRot != player.getYRot()) { + player.absSnapRotationTo(targetYRot, targetXRot); + } + + Vec3 from = player.getEyePosition(); + Vec3 delta = player.getViewVector(1.0F).scale(player.blockInteractionRange()); + Vec3 to = from.add(delta); + BlockHitResult hitResult = player.level().clip(new ClipContext(from, to, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (hitResult.getType() != Type.BLOCK) { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, itemStack, hand); + cancelled = event.useItemInHand() == Result.DENY; + } else { + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(hitResult.getBlockPos()) + && player.gameMode.interactHand == hand + && ItemStack.isSameItemSameComponents(player.gameMode.interactItemStack, itemStack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + Action.RIGHT_CLICK_BLOCK, + hitResult.getBlockPos(), + hitResult.getDirection(), + itemStack, + true, + hand, + hitResult.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } + + if (cancelled) { + player.resyncUsingItem(player); + if (MCUtil.clientPredictsInteraction(player, Blocks.AIR.defaultBlockState(), itemStack)) { + player.containerMenu.sendAllDataToRemote(); + } else { + player.containerMenu.forceHeldSlotAndArmor(hand); + } + + return; + } + + itemStack = player.getItemInHand(hand); + if (itemStack.isEmpty()) { + return; + } + + InteractionResult result = player.gameMode.useItem(player, level, itemStack, hand); + afterUse.accept(result); + if (result instanceof Success success && success.swingSource() == SwingSource.SERVER) { + player.swing(hand, true); + } + } + } + } + } + } + } + + private static void callBaseEntityEvents(RelayedPacketWrapper relayedPacket, PatchedServerGamePacketListener.BaseEntityEventCallback callback) { + ModelBone hitBone = null; + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(relayedPacket.getOriginalId()); + if (activeModel == null) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(relayedPacket.getRelayedId()); + if (hitbox != null) { + hitBone = hitbox.getBone(); + activeModel = hitBone.getActiveModel(); + } + } + + if (activeModel != null) { + BaseEntity base = activeModel.getModeledEntity().getBase(); + callback.call(base, activeModel, hitBone); + } + } + + @FunctionalInterface + private interface BaseEntityEventCallback { + void call(BaseEntity var1, ActiveModel var2, ModelBone var3); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/RelayedPacketWrapper.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/RelayedPacketWrapper.java new file mode 100644 index 0000000..b06878d --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/RelayedPacketWrapper.java @@ -0,0 +1,24 @@ +package com.ticxo.modelengine.v26_2.network.patch; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ServerGamePacketListener; + +public abstract class RelayedPacketWrapper> implements Packet { + private final int relayedId; + private final T original; + + protected RelayedPacketWrapper(int relayedId, T original) { + this.relayedId = relayedId; + this.original = original; + } + + abstract int getOriginalId(); + + public int getRelayedId() { + return this.relayedId; + } + + public T getOriginal() { + return this.original; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/ServerboundAttackPacketWrapper.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/ServerboundAttackPacketWrapper.java new file mode 100644 index 0000000..57aabf0 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/ServerboundAttackPacketWrapper.java @@ -0,0 +1,28 @@ +package com.ticxo.modelengine.v26_2.network.patch; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundAttackPacket; +import org.jetbrains.annotations.NotNull; + +public class ServerboundAttackPacketWrapper extends RelayedPacketWrapper { + public ServerboundAttackPacketWrapper(int relayedId, ServerboundAttackPacket original) { + super(relayedId, original); + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_ATTACK; + } + + public void handle(ServerGamePacketListener listener) { + PatchedServerGamePacketListener.handleAttack(this, listener); + } + + @Override + public int getOriginalId() { + return this.getOriginal().entityId(); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/ServerboundInteractPacketWrapper.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..9b2e666 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,49 @@ +package com.ticxo.modelengine.v26_2.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; + +public class ServerboundInteractPacketWrapper extends RelayedPacketWrapper { + public ServerboundInteractPacketWrapper(int relayedId, ServerboundInteractPacket original) { + super(relayedId, original); + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_INTERACT; + } + + public void handle(ServerGamePacketListener listener) { + PatchedServerGamePacketListener.handleInteract(this, listener); + } + + @Override + public int getOriginalId() { + return this.getOriginal().entityId(); + } + + public InteractionHand getHand() { + return this.getOriginal().hand(); + } + + public boolean isUsingSecondaryAction() { + return this.getOriginal().usingSecondaryAction(); + } + + public Vec3 getLocation() { + return this.getOriginal().location(); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.getOriginalId()) != null || tracker.getEntityRelay(this.getOriginalId()) != null; + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/BulkEntityDataEncoder.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..f829174 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v26_2.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/Bundler.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/Bundler.java new file mode 100644 index 0000000..548b421 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v26_2.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.getLast(); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection> packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.getLast(); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet packet : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/NetworkUtils.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/NetworkUtils.java new file mode 100644 index 0000000..fc24d58 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/NetworkUtils.java @@ -0,0 +1,362 @@ +package com.ticxo.modelengine.v26_2.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v26_2.entity.EntityContainer; +import com.ticxo.modelengine.v26_2.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.GameProtocols.Context; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static final ProtocolInfo CLIENTBOUND_CODEC = GameProtocols.CLIENTBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + public static final ProtocolInfo SERVERBOUND_CODEC = GameProtocols.SERVERBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess()), new Context() { + public boolean hasInfiniteMaterials() { + return false; + } + + public boolean canUseCommandBlocks() { + return false; + } + }); + private static final Map, Constructor> PACKET_CONSTRUCTOR = new HashMap<>(); + + public static RegistryFriendlyByteBuf createByteBuf() { + return new RegistryFriendlyByteBuf(Unpooled.buffer(), MinecraftServer.getServer().registryAccess()); + } + + public static RegistryFriendlyByteBuf createByteBuf(Consumer consumer) { + RegistryFriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static > T create(Class clazz, RegistryFriendlyByteBuf buf) { + Constructor constructor = PACKET_CONSTRUCTOR.computeIfAbsent(clazz, aClass -> { + try { + Constructor c = aClass.getDeclaredConstructor(RegistryFriendlyByteBuf.class); + c.setAccessible(true); + return c; + } catch (NoSuchMethodException var4x) { + try { + Constructor cx = aClass.getDeclaredConstructor(FriendlyByteBuf.class); + cx.setAccessible(true); + return cx; + } catch (NoSuchMethodException var3) { + throw new RuntimeException(var3); + } + } + }); + + try { + return (T)constructor.newInstance(buf); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException var4) { + throw new RuntimeException(var4); + } + } + + public static FriendlyByteBuf readServerbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + SERVERBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static FriendlyByteBuf readClientbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + CLIENTBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityTypes.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityTypes.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createCameraPivotSpawn(int id, UUID uuid, Vector3f pos, float height) { + ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket( + id, uuid, pos.x, pos.y - height, pos.z, 0.0F, 0.0F, EntityTypes.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createCameraPivotTeleport(int id, Vector3f pos, float height) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - height, pos.z); + ClientboundEntityPositionSyncPacket packet = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createDisplayPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - 0.375, pos.z); + ClientboundEntityPositionSyncPacket tpHigher = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + container = EntityContainer.of(id); + container.setId(id); + container.setPosRaw(pos.x, pos.y - 0.5, pos.z); + ClientboundEntityPositionSyncPacket tpLower = new ClientboundEntityPositionSyncPacket( + container.getId(), PositionMoveRotation.of(container), container.onGround() + ); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Object createCameraPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos, float height) { + if (codec == null) { + return createCameraPivotTeleport(id, pos, height); + } else { + return switch (codec.update(pos.x, pos.y - height, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE -> createCameraPivotTeleport(id, pos, height); + }; + } + } + + public static Packets.PacketSupplier createDisplayPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y, pos.z); + return playerUUID -> new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + public static Packets.PacketSupplier lodWrapper( + ModeledEntity modeledEntity, BiFunction> packetFunction + ) { + return uuid -> { + AnimationLODHandler.LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/PacketInterceptor.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..49960eb --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/PacketInterceptor.java @@ -0,0 +1,89 @@ +package com.ticxo.modelengine.v26_2.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor

    { + private final Map>, PacketInterceptor

    .Modifier>> registry = Maps.newConcurrentMap(); + private final Map>, PacketInterceptor

    .Listener>> postRegistry = Maps.newConcurrentMap(); + + public > PacketInterceptor

    register(Class clazz, Function> function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public > PacketInterceptor

    registerPost(Class clazz, Function>> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor

    .Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection> acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor

    .Listener listener = this.postRegistry.get(original.getClass()); + return (Collection>)(listener != null ? listener.listen(original) : List.of()); + } + } + + class Listener> { + private final Class clazz; + private final Function>> function; + + public Collection> listen(Packet original) { + try { + Collection> collection = this.function.apply(this.clazz.cast(original)); + return (Collection>)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(final Class clazz, final Function>> function) { + Objects.requireNonNull(PacketInterceptor.this); + super(); + this.clazz = clazz; + this.function = function; + } + } + + class Modifier> { + private final Class clazz; + private final Function> function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(final Class clazz, final Function> function) { + Objects.requireNonNull(PacketInterceptor.this); + super(); + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/Packets.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/Packets.java new file mode 100644 index 0000000..015a325 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v26_2.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/HeldItemParser.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..23be372 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/HeldItemParser.java @@ -0,0 +1,186 @@ +package com.ticxo.modelengine.v26_2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v26_2.entity.EntityContainer; +import com.ticxo.modelengine.v26_2.entity.EntityUtils; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Quaternionf; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapToInt(HeldItemRenderer.Item::getId)) + )) + ); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Map items = renderer.getRendered(); + IntArrayList entityIds = IntArrayList.toList(items.values().stream().mapToInt(HeldItemRenderer.Item::getId)); + entityIds.add(renderer.getId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityTypes.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + return new ClientboundSetEntityDataPacket(renderer.getId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, HeldItemRenderer.Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(HeldItemRenderer.Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(11); + if (spawn) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, this.viewRange)); + } else if (renderer.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + renderer.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), spawn); + renderer.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), spawn); + renderer.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getRotation() + .ifDirty( + quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf.rotateY((float) Math.PI, new Quaternionf()))), + spawn + ); + renderer.getModel() + .ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + renderer.getDisplay() + .ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getId(), entityData); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location loc = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(loc.getX(), loc.getY(), loc.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ(), false); + case ABSOLUTE: + } + } + + EntityContainer container = EntityContainer.of(renderer.getId()); + container.setPosRaw(loc.getX(), loc.getY(), loc.getZ()); + return new ClientboundEntityPositionSyncPacket(container.getId(), PositionMoveRotation.of(container), container.onGround()); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getId(), renderer.getPassengers())); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/LeashParser.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/LeashParser.java new file mode 100644 index 0000000..fbe4570 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/LeashParser.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.v26_2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.v26_2.entity.EntityContainer; +import com.ticxo.modelengine.v26_2.entity.EntityUtils; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Map leashes = renderer.getRendered(); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(IntArrayList.toList(leashes.values().stream().mapMultiToInt((leash, intConsumer) -> { + intConsumer.accept(leash.getLeashId()); + intConsumer.accept(leash.getPivotId()); + })))); + } + } + + private Packets.PacketSupplier pivotSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + + private ClientboundAddEntityPacket leashSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y - 0.45, pos.z - 0.2, 0.0F, 0.0F, EntityTypes.BAT, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetEntityDataPacket leashData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getLeashId(), EntityUtils.DEFAULT_BAT_DATA); + } + + private ClientboundSetPassengersPacket mount(LeashRenderer.Leash renderer) { + ArrayList passengers = new ArrayList<>(1); + passengers.add(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), passengers)); + } + + private Object move(LeashRenderer.Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + } + + private ClientboundSetEntityLinkPacket link(LeashRenderer.Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(EntityContainer.of(renderer.getLeashId()), EntityContainer.of(renderer.getConnected().get())); + } + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/MountParser.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/MountParser.java new file mode 100644 index 0000000..72a1733 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/MountParser.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.v26_2.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_2.entity.EntityContainer; +import com.ticxo.modelengine.v26_2.entity.EntityUtils; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getMountId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Collection mounts = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(mounts.size() * 2); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getMountId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_PIVOT_DISPLAY_DATA); + } + + private ClientboundAddEntityPacket mountSpawn(MountRenderer.Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityTypes.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getMountId())); + } + + private ClientboundSetPassengersPacket mount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getMountId(), renderer.getPassengers())); + } + + private Packets.PacketSupplier pivotMove(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(MountRenderer.Mount renderer) { + return new Rot(renderer.getMountId(), renderer.getYaw().get(), (byte)0, false); + } + + private ClientboundSetEntityDataPacket mountHealth(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, renderer.getHealth().get()))); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(MountRenderer.Mount renderer) { + AttributeInstance attributeInstance = new AttributeInstance(Attributes.MAX_HEALTH, onDirty -> {}); + attributeInstance.setBaseValue(renderer.getMaxHealth().get().floatValue()); + return new ClientboundUpdateAttributesPacket(renderer.getMountId(), Lists.newArrayList(new AttributeInstance[]{attributeInstance})); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/NameTagParser.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..a30e50d --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/NameTagParser.java @@ -0,0 +1,184 @@ +package com.ticxo.modelengine.v26_2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.v26_2.entity.EntityContainer; +import com.ticxo.modelengine.v26_2.entity.EntityUtils; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTagRenderer.NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTagRenderer.NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Collection nameTags = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(nameTags.size() * 2); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + return !spawn ? null : new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTagRenderer.NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(7); + renderer.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + renderer.getTranslate().ifDirty(flag -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getScale().ifDirty(flag -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getTextOpacity().ifDirty(flag -> entityData.add(new DataValue(26, EntityDataSerializers.BYTE, flag)), spawn); + renderer.getBackgroundColor().ifDirty(flag -> entityData.add(new DataValue(25, EntityDataSerializers.INT, flag)), spawn); + renderer.getLineWidth().ifDirty(flag -> entityData.add(new DataValue(24, EntityDataSerializers.INT, flag)), spawn); + renderer.getStyle().ifDirty(flags -> entityData.add(new DataValue(27, EntityDataSerializers.BYTE, flags)), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new MatchException(null, null); + }; + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, value)); + }, spawn); + renderer.getJsonString() + .ifDirty( + jsonString -> { + if (jsonString == null) { + entityData.add(new DataValue(23, EntityDataSerializers.COMPONENT, Component.empty())); + } else { + entityData.add( + new DataValue(23, EntityDataSerializers.COMPONENT, Optional.ofNullable(CraftChatMessage.fromJSON(jsonString)).orElse(Component.empty())) + ); + } + }, + spawn + ); + renderer.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getTagId(), entityData); + } + } + + private Object pivotMove(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTagRenderer.NameTag renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getTagId())); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/SegmentParser.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..352aeda --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/SegmentParser.java @@ -0,0 +1,205 @@ +package com.ticxo.modelengine.v26_2.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_2.entity.EntityContainer; +import com.ticxo.modelengine.v26_2.entity.EntityUtils; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (SegmentRenderer.Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + IntArrayList destroy = new IntArrayList(); + + for (SegmentRenderer.Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(destroy))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(SegmentRenderer.Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SegmentRenderer.Pivot pivot) { + return new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(SegmentRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(SegmentRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(SegmentRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + ArrayList> entityData = new ArrayList<>(13); + if (force) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } else if (bone.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : 1)), force); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), force); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/SubHitboxParser.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..769f446 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/behavior/SubHitboxParser.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v26_2.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.v26_2.entity.EntityContainer; +import com.ticxo.modelengine.v26_2.entity.EntityUtils; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitboxRenderer.SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Collection subHitboxes = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(subHitboxes.size() * 2); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private Object pivotMove(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getHitboxId())); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitboxRenderer.SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitboxRenderer.SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(4); + renderer.getWidth().ifDirty(width -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, width)), spawn); + renderer.getHeight().ifDirty(height -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, height)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getHitboxId(), entityData); + } + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/model/DisplayParser.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/model/DisplayParser.java new file mode 100644 index 0000000..6fded2d --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/model/DisplayParser.java @@ -0,0 +1,791 @@ +package com.ticxo.modelengine.v26_2.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_2.entity.EntityContainer; +import com.ticxo.modelengine.v26_2.entity.EntityUtils; +import com.ticxo.modelengine.v26_2.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_2.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static StreamCodec CUSTOM_PAYLOAD_CODEC; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + if (renderer.hasGlowAudience()) { + this.updateAudienceGlow(renderer, data.getTracking().keySet(), data.getStartTracking(), this.noCullForcePlayers); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + private void updateAudienceGlow(DisplayRenderer renderer, Set current, Set startTracking, Set forceUpdates) { + for (DisplayBone bone : renderer.getRendered().values()) { + Set audience = bone.getGlowAudience().get(); + if (audience != null) { + boolean changed = bone.isAudienceGlowDirty(); + if (changed || !startTracking.isEmpty() || !forceUpdates.isEmpty()) { + boolean glowing = bone.getAudienceGlowing().get(); + int color = bone.getAudienceGlowColor().get(); + Set on = new HashSet<>(); + Set off = new HashSet<>(); + if (changed) { + for (UUID uuid : current) { + if (glowing && audience.contains(uuid)) { + on.add(uuid); + } else { + off.add(uuid); + } + } + + bone.clearAudienceGlowDirty(); + } else if (glowing) { + for (UUID uuidx : startTracking) { + if (audience.contains(uuidx)) { + on.add(uuidx); + } + } + + for (UUID uuidxx : forceUpdates) { + if (audience.contains(uuidxx)) { + on.add(uuidxx); + } + } + } + + if (!on.isEmpty() || !off.isEmpty()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + int id = boneData.getId(); + if (!on.isEmpty()) { + NetworkUtils.send(on, this.audienceGlowData(id, true, color)); + } + + if (!off.isEmpty()) { + NetworkUtils.send(off, this.audienceGlowData(id, false, color)); + } + } + } + } + } + } + } + + private ClientboundSetEntityDataPacket audienceGlowData(int entityId, boolean glowing, int color) { + ArrayList> entityData = new ArrayList<>(2); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(glowing ? 96 : 32))); + if (glowing) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + + return new ClientboundSetEntityDataPacket(entityId, entityData); + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + set.add((Packet)this.pivotCameraResize(pivot)); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(destroy)))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(hitboxDestroy)))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)(u -> this.displayData(u, null, boneData, false, transformOnly))); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + AnimationLODHandler.LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + RegistryFriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(RegistryFriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CODEC == null) { + Field field = ClientboundCustomPayloadPacket.class.getField("GAMEPLAY_STREAM_CODEC"); + field.setAccessible(true); + CUSTOM_PAYLOAD_CODEC = (StreamCodec)field.get(null); + } + + return (Packet)CUSTOM_PAYLOAD_CODEC.decode(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData( + BulkEntityDataEncoder encoder, + UUID uuid, + @Nullable AnimationLODHandler.LODTracker tracker, + DisplayBone.BoneData boneData, + boolean force, + boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + + for (DisplayBone bone : new ArrayList<>(renderer.getRendered().values())) { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + } + + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? new ClientboundSetEntityDataPacket(pivot.getId(), this.cameraPivotData(pivot.getCameraHeight().get())) + : new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private List> cameraPivotData(float height) { + return List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(8, EntityDataSerializers.FLOAT, 0.0F), + new DataValue(9, EntityDataSerializers.FLOAT, height) + ); + } + + private ClientboundSetPassengersPacket pivotMount(DisplayRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(DisplayRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundSetEntityDataPacket pivotCameraResize(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() && pivot.getCameraHeight().isDirty() + ? new ClientboundSetEntityDataPacket(pivot.getId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, pivot.getCameraHeight().get()))) + : null; + } + + private ClientboundAddEntityPacket displaySpawn(DisplayRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData( + UUID uuid, @Nullable AnimationLODHandler.LODTracker tracker, DisplayBone.BoneData boneData, boolean force, boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + ArrayList> entityData = new ArrayList<>(13); + if (!force && update != 0) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : lodTick)), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + entityData.add(new DataValue(16, EntityDataSerializers.INT, val)); + } + }, force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + } + }, force); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + + private ClientboundSetEntityDataPacket displayVisibleData(DisplayBone.BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)))); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color))); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val))); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F))); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)))); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()))); + this.cleanupQueue.add(bone::clearDirty); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(DisplayRenderer.Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(DisplayRenderer.Hitbox hitbox) { + return !hitbox.isPivotVisible() ? null : new ClientboundSetEntityDataPacket(hitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket hitboxSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(4); + hitbox.getWidth().ifDirty(val -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, val)), spawn); + hitbox.getHeight().ifDirty(val -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getHitboxId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(2); + hitbox.getShadowRadius().ifDirty(val -> entityData.add(new DataValue(18, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getShadowId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(DisplayRenderer.Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(DisplayRenderer.Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + return new ClientboundSetPassengersPacket(EntityContainer.of(hitbox.getPivotId(), passengers)); + } + } +} diff --git a/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/vfx/VFXDisplayParser.java b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..a9b1115 --- /dev/null +++ b/nms/v26_2/src/main/java/com/ticxo/modelengine/v26_2/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,124 @@ +package com.ticxo.modelengine.v26_2.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v26_2.entity.EntityContainer; +import com.ticxo.modelengine.v26_2.entity.EntityUtils; +import com.ticxo.modelengine.v26_2.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_2.network.utils.Packets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(new int[]{vfx.getPivotId(), vfx.getModelId()})); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXDisplayRenderer.VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetEntityDataPacket(vfx.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXDisplayRenderer.VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXDisplayRenderer.VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(9); + if (spawn) { + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)32)); + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, 4096.0F)); + entityData.add(new DataValue(24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal())); + } else if (vfx.isModelDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + vfx.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + vfx.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + vfx.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + vfx.clearModelDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(vfx.getModelId(), entityData); + } + } + + private Object teleport(VFXDisplayRenderer.VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetPassengersPacket(EntityContainer.of(vfx.getPivotId(), vfx.getModelId())); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSFields.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSFields.java new file mode 100644 index 0000000..c343c40 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSFields.java @@ -0,0 +1,56 @@ +package com.ticxo.modelengine.v26_3; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.level.Level; + +public enum NMSFields implements ReflectionUtils.ReflectionEnum { + ENTITY_dimensions(Entity.class, "dimensions", "dimensions"), + ENTITY_eyeHeight(Entity.class, "eyeHeight", "eyeHeight"), + ENTITY_bukkitEntity(Entity.class, "bukkitEntity", "bukkitEntity"), + LIVING_ENTITY_noJumpDelay(LivingEntity.class, "noJumpDelay", "noJumpDelay"), + LIVING_ENTITY_jumping(LivingEntity.class, "jumping", "jumping"), + MOB_lookControl(Mob.class, "lookControl", "lookControl"), + MOB_moveControl(Mob.class, "moveControl", "moveControl"), + MOB_navigation(Mob.class, "navigation", "navigation"), + MOB_goalSelector(Mob.class, "goalSelector", "goalSelector"), + MOB_bodyRotationControl(Mob.class, "bodyRotationControl", "bodyRotationControl"), + SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating(ServerGamePacketListenerImpl.class, "clientIsFloating", "clientIsFloating"), + MOVE_CONTROL_operation(MoveControl.class, "operation", "operation"), + TRACKED_ENTITY_range(TrackedEntity.class, "range", "range"), + LEVEL_soundSeedGenerator(Level.class, "soundSeedGenerator", "soundSeedGenerator"), + CLIENTBOUND_MOVE_ENTITY_PACKET_entityId(ClientboundMoveEntityPacket.class, "entityId", "entityId"), + CLIENTBOUND_ROTATE_HEAD_PACKET_entityId(ClientboundRotateHeadPacket.class, "entityId", "entityId"); + + private final Class target; + private final String obfuscated; + private final String mapped; + + private NMSFields(final Class target, final String obfuscated, final String mapped) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSHandler_v26_3.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSHandler_v26_3.java new file mode 100644 index 0000000..168e2bb --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSHandler_v26_3.java @@ -0,0 +1,225 @@ +package com.ticxo.modelengine.v26_3; + +import com.mojang.math.MatrixUtil; +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.generator.assets.ItemModelData; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.NMSHandler; +import com.ticxo.modelengine.api.nms.RenderParsers; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v26_3.entity.EntityContainer; +import com.ticxo.modelengine.v26_3.entity.EntityHandlerImpl; +import com.ticxo.modelengine.v26_3.network.NetworkHandlerImpl; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_3.parser.behavior.LeashParser; +import com.ticxo.modelengine.v26_3.parser.behavior.MountParser; +import com.ticxo.modelengine.v26_3.parser.behavior.NameTagParser; +import com.ticxo.modelengine.v26_3.parser.behavior.SegmentParser; +import com.ticxo.modelengine.v26_3.parser.behavior.SubHitboxParser; +import com.ticxo.modelengine.v26_3.parser.model.DisplayParser; +import com.ticxo.modelengine.v26_3.parser.vfx.VFXDisplayParser; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.components.CustomModelDataComponent; +import org.bukkit.util.Transformation; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class NMSHandler_v26_3 implements NMSHandler { + private final EntityHandler entityHandler = new EntityHandlerImpl(); + private final NetworkHandler networkHandler = new NetworkHandlerImpl(); + private final RenderParsers globalParsers = this.createParsers(); + private final VFXDisplayParser vfxDisplayParser = new VFXDisplayParser(); + private boolean manualTranslucencyOrder; + private boolean forceCMD; + + public NMSHandler_v26_3() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + public void updateConfig() { + this.manualTranslucencyOrder = ConfigProperty.MANUAL_TRANSLUCENCY_ORDER.getBoolean(); + this.forceCMD = ConfigProperty.FORCE_CMD.getBoolean(); + } + + @Override + public RenderParsers createParsers() { + RenderParsers parsers = new RenderParsers(); + parsers.registerModelParser(renderer -> renderer instanceof DisplayRenderer, DisplayParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof MountRenderer, MountParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof LeashRenderer, LeashParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof NameTagRenderer, NameTagParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SubHitboxRenderer, SubHitboxParser::new); + parsers.registerBehaviorParser(renderer -> renderer instanceof SegmentRenderer, SegmentParser::new); + return parsers; + } + + @Override + public void sendPivotOverrides() { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + + for (PivotOverride override : registry.getAll()) { + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(override.getUuid()); + BukkitEntityData data = modeledEntity != null && modeledEntity.getBase().getData() instanceof BukkitEntityData d ? d : null; + boolean passengersDirty = override.getPassengers().isDirty(); + Set lateTrackers = data != null ? data.getStartTracking() : Set.of(); + if (passengersDirty || !lateTrackers.isEmpty()) { + RegistryFriendlyByteBuf byteBuf = NetworkUtils.createByteBuf(buf -> { + buf.writeVarInt(override.getId()); + Collection list = override.getPassengers().get(); + ArrayList allPassengers = new ArrayList<>(list); + if (modeledEntity != null) { + List basePassengers = modeledEntity.getBase().getPassengers(); + int[] snapshot = new int[basePassengers.size()]; + int i = 0; + + for (Entity passenger : basePassengers) { + int pid = passenger.getEntityId(); + snapshot[i++] = pid; + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + + override.setBasePassengerSnapshot(snapshot); + } else { + for (int pid : override.getBasePassengerSnapshot()) { + if (!allPassengers.contains(pid)) { + allPassengers.add(pid); + } + } + } + + buf.writeVarInt(allPassengers.size()); + allPassengers.forEach(buf::writeVarInt); + }); + Set recipients; + if (data == null) { + recipients = ServerInfo.getOnlinePlayers(); + } else if (passengersDirty) { + recipients = new HashSet<>(data.getMutableTracking().keySet()); + recipients.addAll(lateTrackers); + } else { + recipients = lateTrackers; + } + + NetworkUtils.send(recipients, NetworkUtils.create(ClientboundSetPassengersPacket.class, byteBuf)); + override.getPassengers().clearDirty(); + } + } + } + + @Override + public Set createStack(ItemModelData data, ItemModelData.Context context) { + if (this.forceCMD) { + return NMSHandler.super.createStack(data, context); + } else { + ItemStack item = new ItemStack(this.manualTranslucencyOrder && !data.isTranslucent() ? Material.GLASS : Material.BONE); + item.editMeta(itemMeta -> { + itemMeta.setItemModel(data.getSingleComposite().model()); + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(context.color())); + if (data.getVariant() != null) { + cmdComp.setStrings(List.of(data.getVariant())); + } + + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return Set.of(item); + } + } + + @Override + public boolean colorStack(ItemStack stack, Color color) { + stack.editMeta(itemMeta -> { + CustomModelDataComponent cmdComp = itemMeta.getCustomModelDataComponent(); + cmdComp.setColors(List.of(color)); + itemMeta.setCustomModelDataComponent(cmdComp); + }); + return true; + } + + @Override + public void applyPlayerHeadItemModel(ItemStack stack) { + stack.editMeta(meta -> meta.setItemModel(this.getPlayerHeadModelKey())); + } + + @Override + public ModelRendererParser getModelRendererParser(T renderer) { + return this.globalParsers.getModelParser(renderer); + } + + @Override + public BehaviorRendererParser getBehaviorRendererParser(T renderer) { + return this.globalParsers.getBehaviorParser(renderer); + } + + @Override + public VFXRendererParser getVFXRendererParser(T renderer) { + return renderer instanceof VFXDisplayRenderer ? (VFXRendererParser)(Object)this.vfxDisplayParser : null; + } + + @Override + public void sendMountPassengerUpdate(Set targets, int mountId, Collection passengerIds) { + ClientboundSetPassengersPacket packet = new ClientboundSetPassengersPacket(EntityContainer.of(mountId, passengerIds)); + + for (UUID target : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(packet)); + } + } + + @Override + public Transformation decompose(Matrix4f transform) { + Vector3f translation = new Vector3f(); + Quaternionf leftRotation = new Quaternionf(); + Vector3f scale = new Vector3f(); + Quaternionf rightRotation = new Quaternionf(); + MatrixUtil.svdDecompose(transform, translation, leftRotation, scale, rightRotation); + return new Transformation(translation, leftRotation, scale, rightRotation); + } + + @Override + public EntityHandler getEntityHandler() { + return this.entityHandler; + } + + @Override + public NetworkHandler getNetworkHandler() { + return this.networkHandler; + } + + @Override + public RenderParsers getGlobalParsers() { + return this.globalParsers; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSMethods.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSMethods.java new file mode 100644 index 0000000..f1075f5 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/NMSMethods.java @@ -0,0 +1,48 @@ +package com.ticxo.modelengine.v26_3; + +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemStack; + +public enum NMSMethods implements ReflectionUtils.MethodEnum { + TRACKED_ENTITY_getEffectiveRange(TrackedEntity.class, "b", "getEffectiveRange"), + SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit(ServerGamePacketListenerImpl.class, "checkLimit", "checkLimit", long.class), + INSTRUMENT_ITEM_getInstrument(InstrumentItem.class, "a", "getInstrument", ItemStack.class), + ENTITY_getPassengerAttachmentPoint(Entity.class, "a", "getPassengerAttachmentPoint", Entity.class, EntityDimensions.class, float.class); + + private final Class target; + private final String obfuscated; + private final String mapped; + private final Class[] parameterClasses; + + private NMSMethods(Class target, String obfuscated, String mapped, Class... parameterClasses) { + this.target = target; + this.obfuscated = obfuscated; + this.mapped = mapped; + this.parameterClasses = parameterClasses; + } + + @Override + public Class getTarget() { + return this.target; + } + + @Override + public String getObfuscated() { + return this.obfuscated; + } + + @Override + public String getMapped() { + return this.mapped; + } + + @Override + public Class[] getParameterClasses() { + return this.parameterClasses; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityContainer.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityContainer.java new file mode 100644 index 0000000..ce08720 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityContainer.java @@ -0,0 +1,60 @@ +package com.ticxo.modelengine.v26_3.entity; + +import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import net.minecraft.network.syncher.SynchedEntityData.Builder; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.ApiStatus.Internal; + +@Internal +public class EntityContainer extends Entity { + public static EntityContainer of(int id) { + return new EntityContainer(id); + } + + public static Entity of(int id, int... passengerIds) { + EntityContainer container = of(id); + container.setPassengers(Arrays.stream(passengerIds).mapToObj(EntityContainer::new).toList()); + return container; + } + + public static Entity of(int id, Collection passengerIds) { + EntityContainer container = of(id); + container.setPassengers(passengerIds.stream().map(EntityContainer::new).toList()); + return container; + } + + private EntityContainer(int id) { + super(EntityTypes.INTERACTION, MinecraftServer.getServer().overworld()); + this.setId(id); + this.setPosRaw(0.0, 0.0, 0.0); + this.setRot(0.0F, 0.0F); + this.setOnGround(false); + } + + protected void setPassengers(List passengers) { + this.passengers = ImmutableList.copyOf(passengers); + } + + protected void defineSynchedData(@NotNull Builder builder) { + } + + public boolean hurtServer(ServerLevel world, DamageSource source, float amount) { + return false; + } + + protected void readAdditionalSaveData(ValueInput valueInput) { + } + + protected void addAdditionalSaveData(ValueOutput valueOutput) { + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityHandlerImpl.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityHandlerImpl.java new file mode 100644 index 0000000..202e6b1 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityHandlerImpl.java @@ -0,0 +1,832 @@ +package com.ticxo.modelengine.v26_3.entity; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.Hitbox; +import com.ticxo.modelengine.api.entity.data.BukkitEntityData; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.EntityState; +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.TempTrackedEntity; +import com.ticxo.modelengine.api.utils.RaceConditionUtil; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.config.DebugToggle; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v26_3.NMSFields; +import com.ticxo.modelengine.v26_3.NMSMethods; +import com.ticxo.modelengine.v26_3.entity.controller.BodyRotationControlWrapper; +import com.ticxo.modelengine.v26_3.entity.controller.LookControlWrapper; +import com.ticxo.modelengine.v26_3.entity.controller.MoveControlWrapper; +import com.ticxo.modelengine.v26_3.entity.hitbox.HitboxEntityImpl; +import com.ticxo.modelengine.v26_3.entity.navigation.AmphibiousNavigationWrapper; +import com.ticxo.modelengine.v26_3.entity.navigation.FlyingNavigationWrapper; +import com.ticxo.modelengine.v26_3.entity.navigation.GroundNavigationWrapper; +import com.ticxo.modelengine.v26_3.entity.navigation.WallClimberNavigationWrapper; +import com.ticxo.modelengine.v26_3.entity.navigation.WaterBoundNavigationWrapper; +import com.ticxo.modelengine.v26_3.network.patch.PatchedServerGamePacketListener; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_3.network.utils.Packets; +import io.papermc.paper.adventure.PaperAdventure; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.kyori.adventure.text.Component; +import net.minecraft.core.Holder; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult.Fail; +import net.minecraft.world.InteractionResult.Pass; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.TryEmptyHandInteraction; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.AreaEffectCloud; +import net.minecraft.world.entity.EntityAttachments; +import net.minecraft.world.entity.EntityDimensions; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.goal.WrappedGoal; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.entity.ai.navigation.PathNavigation; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.entity.decoration.ArmorStand; +import net.minecraft.world.item.Instrument; +import net.minecraft.world.item.InstrumentItem; +import net.minecraft.world.item.ItemUseAnimation; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.World; +import org.bukkit.Particle.DustOptions; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class EntityHandlerImpl implements EntityHandler { + private static boolean usePaperClipMethod; + private static final MethodHandle JUMPING_GETTER = createJumpingGetter(); + private final Set forceInvisible = ConcurrentHashMap.newKeySet(); + private double forceRenderWidth; + private double forceRenderHeight; + private ArmorStand dummyArmorStand; + private AreaEffectCloud dummyCloud; + + private static MethodHandle createJumpingGetter() { + Field field = ReflectionUtils.getField(NMSFields.LIVING_ENTITY_jumping); + if (field == null) { + return null; + } else { + try { + return MethodHandles.lookup().unreflectGetter(field); + } catch (IllegalAccessException var2) { + var2.printStackTrace(); + return null; + } + } + } + + public EntityHandlerImpl() { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(this::updateConfig); + } + + @Override + public void updateConfig() { + this.forceRenderWidth = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_WIDTH.getDouble(); + this.forceRenderHeight = ConfigProperty.BLOCK_CULL_IGNORE_SIZE_HEIGHT.getDouble(); + usePaperClipMethod = ConfigProperty.BLOCK_CULL_USE_PAPER_CLIP.getBoolean(); + } + + @Override + public int getNextEntityId() { + return CraftMagicNumbers.INSTANCE.nextEntityId(MinecraftServer.getServer().overworld().getWorld()); + } + + @Override + public int getEntityId(Entity entity) { + return EntityUtils.nms(entity).getId(); + } + + @Override + public void setHitbox(Entity entity, @NotNull Hitbox hitbox) { + float width = (float)hitbox.getMaxWidth(); + float height = (float)hitbox.getHeight(); + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + EntityDimensions box = new EntityDimensions(width, height, (float)hitbox.getEyeHeight(), EntityAttachments.createDefault(width, height), true); + ReflectionUtils.set(nms, NMSFields.ENTITY_dimensions, box); + ReflectionUtils.set(nms, NMSFields.ENTITY_eyeHeight, (float)hitbox.getEyeHeight()); + nms.setBoundingBox(box.makeBoundingBox(nms.position())); + } + + @Override + public void setStepHeight(Entity entity, double height) { + if (EntityUtils.nms(entity) instanceof LivingEntity living) { + living.getAttributes().registerAttribute(Attributes.STEP_HEIGHT); + Objects.requireNonNull(living.getAttribute(Attributes.STEP_HEIGHT)).setBaseValue(height); + } + } + + @Override + public double getStepHeight(Entity entity) { + return EntityUtils.nms(entity).maxUpStep(); + } + + @Override + public void setPosition(Entity entity, double x, double y, double z) { + EntityUtils.nms(entity).setPos(x, y, z); + } + + @Override + public void movePassenger(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyArmorStand == null) { + this.dummyArmorStand = new ArmorStand(EntityTypes.ARMOR_STAND, nmsEntity.level()); + this.dummyArmorStand.setMarker(true); + } + + double seatY = y - nmsEntity.getVehicleAttachmentPoint(this.dummyArmorStand).y; + nmsEntity.setPos(x, seatY, z); + nmsEntity.setDeltaMovement(Vec3.ZERO); + nmsEntity.resetFallDistance(); + if (nmsEntity instanceof ServerPlayer player) { + ReflectionUtils.set(player.connection, NMSFields.SERVER_GAME_PACKET_LISTENER_IMPL_clientIsFloating, false); + } + } + + @Override + public void forceSpawn(BaseEntity entity, Player player) { + if (player != null) { + if (entity.getData() instanceof BukkitEntityData bukkitEntityData) { + bukkitEntityData.getTracked().sendPairingData(player); + } + } + } + + @Override + public void forceDespawn(BaseEntity entity, Player player) { + if (player != null) { + NetworkUtils.send(player.getUniqueId(), new ClientboundRemoveEntitiesPacket(new int[]{entity.getEntityId()})); + } + } + + @Override + public void setForcedInvisible(Entity entity, boolean flag) { + if (this.isForcedInvisible(entity) != flag) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + byte data = 0; + + for (int i = 0; i < 8; i++) { + data = TMath.setBit(data, i, nms.getSharedFlag(i)); + } + + if (flag) { + this.forceInvisible.add(entity.getUniqueId()); + data = TMath.setBit(data, 5, true); + } else { + this.forceInvisible.remove(entity.getUniqueId()); + } + + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + this.getEntityId(entity), List.of(new DataValue(0, EntityDataSerializers.BYTE, data)) + ); + NetworkUtils.send(ServerInfo.getOnlinePlayers(), packet); + } + } + + @Override + public boolean isForcedInvisible(UUID uuid) { + return this.forceInvisible.contains(uuid); + } + + @Override + public void clearForcedInvisible(UUID uuid) { + this.forceInvisible.remove(uuid); + } + + @Override + public BodyRotationController wrapBodyRotationControl(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + BodyRotationControlWrapper var5 = new BodyRotationControlWrapper(mob); + return (BodyRotationController)(ReflectionUtils.set(mob, NMSFields.MOB_bodyRotationControl, var5) ? var5 : def.get()); + } else { + return def.get(); + } + } + + @Override + public MoveController wrapMoveController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getMoveControl() instanceof MoveController controller) { + return controller; + } else { + MoveControlWrapper controller = new MoveControlWrapper(mob, mob.getMoveControl()); + return (MoveController)(ReflectionUtils.set(mob, NMSFields.MOB_moveControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public LookController wrapLookController(Entity entity, Supplier def) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + if (mob.getLookControl() instanceof LookController controller) { + return controller; + } else { + LookControlWrapper controller = new LookControlWrapper(mob, mob.getLookControl()); + return (LookController)(ReflectionUtils.set(mob, NMSFields.MOB_lookControl, controller) ? controller : def.get()); + } + } else { + return def.get(); + } + } + + @Override + public void wrapNavigation(Entity entity) { + if (EntityUtils.nms(entity) instanceof Mob mob) { + try { + Field navField = ReflectionUtils.getField(NMSFields.MOB_navigation); + PathNavigation oldNav = mob.getNavigation(); + PathNavigation newNav; + switch (oldNav) { + case WallClimberNavigation wallClimberNavigation: + newNav = new WallClimberNavigationWrapper(mob, wallClimberNavigation); + break; + case GroundPathNavigation groundPathNavigation: + newNav = new GroundNavigationWrapper(mob, groundPathNavigation); + break; + case FlyingPathNavigation flyingPathNavigation: + newNav = new FlyingNavigationWrapper(mob, flyingPathNavigation); + break; + case WaterBoundPathNavigation waterBoundPathNavigation: + newNav = new WaterBoundNavigationWrapper(mob); + break; + case AmphibiousPathNavigation amphibiousPathNavigation: + newNav = new AmphibiousNavigationWrapper(mob, amphibiousPathNavigation); + break; + default: + TLogger.warn("Failed to create custom navigation for " + mob.getType() + ": " + mob.getUUID()); + TLogger.warn("Reason: Navigation class type is " + oldNav.getClass().getSimpleName() + "."); + return; + } + + navField.set(mob, newNav); + GoalSelector goalSelector = (GoalSelector)ReflectionUtils.getField(NMSFields.MOB_goalSelector).get(mob); + RaceConditionUtil.wrapConmod(() -> this.replaceNavigation(goalSelector, newNav)); + } catch (IllegalAccessException var13) { + var13.printStackTrace(); + } + } + } + + private void replaceNavigation(GoalSelector goalSelector, PathNavigation newNav) { + try { + for (WrappedGoal wrappedGoal : goalSelector.getAvailableGoals()) { + Goal goal = wrappedGoal.getGoal(); + + for (Field field : goal.getClass().getDeclaredFields()) { + field = ReflectionUtils.getField(goal.getClass(), field.getName()); + Object f = field.get(goal); + if (f instanceof PathNavigation) { + field.set(goal, newNav); + } + } + } + } catch (IllegalAccessException var11) { + var11.printStackTrace(); + } + } + + @Override + public HitboxEntity createHitbox(Location location, ModelBone bone, SubHitbox subHitbox) { + World bukkitWorld = location.getWorld(); + if (bukkitWorld == null) { + if (bone.getActiveModel().getModeledEntity().getBase().getOriginal() instanceof Entity entity) { + bukkitWorld = entity.getWorld(); + } + + if (bukkitWorld == null) { + return null; + } + } + + ServerLevel level = ((CraftWorld)bukkitWorld).getHandle(); + HitboxEntityImpl entity = new HitboxEntityImpl(level, bone, subHitbox); + entity.queueLocation(new Vector3f().set(location.getX(), location.getY(), location.getZ())); + entity.setPos(location.getX(), location.getY(), location.getZ()); + ModelEngineAPI.setRenderCanceled(entity.getId(), true); + Promise.start(entity.getBukkitEntity()).thenRunSync(() -> { + if (!entity.isRemoved() && entity.isValid()) { + int attempts = 0; + + while (level.getEntity(entity.getUUID()) != null && attempts++ < 8) { + entity.setUUID(UUID.randomUUID()); + } + + if (level.getEntity(entity.getUUID()) != null) { + entity.discard(); + } else { + level.addFreshEntity(entity); + ModelEngineAPI.getInteractionTracker().addHitbox(entity); + } + } + }); + return entity; + } + + @Nullable + @Override + public HitboxEntity castHitbox(Entity entity) { + return EntityUtils.nms(entity) instanceof HitboxEntity hitbox ? hitbox : null; + } + + @Override + public boolean hurt(Entity entity, Object source, float amount) { + if (source instanceof DamageSource damageSource) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (nmsEntity.level() instanceof ServerLevel worldserver) { + return nmsEntity.hurtServer(worldserver, damageSource, amount); + } + } + + throw new RuntimeException("Passed in source is not an NMS DamageSource."); + } + + @Override + public EntityHandler.InteractionResult interact(Entity entity, HumanEntity player, EquipmentSlot hand) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + net.minecraft.world.InteractionResult result = livingEntity.interact( + ((CraftPlayer)player).getHandle(), hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, Vec3.ZERO + ); + + return switch (result) { + case Success success -> success.equals(net.minecraft.world.InteractionResult.SUCCESS_SERVER) + ? EntityHandler.InteractionResult.SUCCESS + : ( + success.equals(net.minecraft.world.InteractionResult.SUCCESS) + ? EntityHandler.InteractionResult.CONSUME_PARTIAL + : EntityHandler.InteractionResult.CONSUME + ); + case TryEmptyHandInteraction ignored -> EntityHandler.InteractionResult.SUCCESS_NO_ITEM_USED; + case Pass ignoredx -> EntityHandler.InteractionResult.PASS; + case Fail ignoredxx -> EntityHandler.InteractionResult.FAIL; + default -> throw new MatchException(null, null); + }; + } else { + return EntityHandler.InteractionResult.FAIL; + } + } + + @Override + public void spawnDynamicHitbox(DynamicHitbox hitbox) { + Vector location = hitbox.getPositionTracker().get(); + final Packets.PacketSupplier pivotSpawn = NetworkUtils.createPivotSpawn( + DynamicHitbox.getPivotId(), DynamicHitbox.getPivotUUID(), location.toVector3f().add(0.0F, -0.5202F, 0.0F) + ); + final ClientboundSetEntityDataPacket pivotData = new ClientboundSetEntityDataPacket( + DynamicHitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA + ); + final ClientboundAddEntityPacket hitboxSpawn = new ClientboundAddEntityPacket( + DynamicHitbox.getHitboxId(), + DynamicHitbox.getHitboxUUID(), + location.getX(), + location.getY() - 0.5202, + location.getZ(), + 0.0F, + 0.0F, + EntityTypes.SLIME, + 0, + Vec3.ZERO, + 0.0 + ); + final ClientboundSetEntityDataPacket hitboxData = new ClientboundSetEntityDataPacket(DynamicHitbox.getHitboxId(), EntityUtils.DEFAULT_SLIME_DATA); + final ClientboundSetPassengersPacket mount = new ClientboundSetPassengersPacket( + EntityContainer.of(DynamicHitbox.getPivotId(), DynamicHitbox.getHitboxId()) + ); + NetworkUtils.sendBundled(Set.of(hitbox.getPlayer().getUniqueId()), new Packets() { + { + Objects.requireNonNull(EntityHandlerImpl.this); + this.add(pivotSpawn); + this.add(pivotData); + this.add(hitboxSpawn); + this.add(hitboxData); + this.add(mount); + } + }); + } + + @Override + public void updateDynamicHitbox(DynamicHitbox hitbox) { + Vector3f vector = hitbox.getPositionTracker().get().toVector3f().add(0.0F, -0.5202F, 0.0F); + NetworkUtils.send( + hitbox.getPlayer().getUniqueId(), NetworkUtils.createPivotTeleport(DynamicHitbox.getPivotId(), vector).supply(hitbox.getPlayer().getUniqueId()) + ); + } + + @Override + public void destroyDynamicHitbox(DynamicHitbox hitbox) { + ClientboundRemoveEntitiesPacket destroy = new ClientboundRemoveEntitiesPacket(new int[]{DynamicHitbox.getHitboxId(), DynamicHitbox.getPivotId()}); + NetworkUtils.send(hitbox.getPlayer().getUniqueId(), destroy); + } + + @Override + public void forceUseItem(Player player, EquipmentSlot hand) { + ItemStack stack = player.getEquipment().getItem(hand); + net.minecraft.world.item.ItemStack nmsStack = ((CraftItemStack)stack).handle; + ServerPlayer nmsPlayer = (ServerPlayer)EntityUtils.nms(player); + ServerGamePacketListenerImpl connection = nmsPlayer.connection; + ServerboundUseItemPacket useItemPacket = new ServerboundUseItemPacket( + hand == EquipmentSlot.HAND ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND, + 0, + nmsPlayer.getYRot(), + nmsPlayer.getXRot(), + System.currentTimeMillis() + ); + PatchedServerGamePacketListener.handleUseItem( + useItemPacket, + connection, + interactionResult -> { + if (nmsStack.getUseAnimation() != ItemUseAnimation.NONE && interactionResult == net.minecraft.world.InteractionResult.CONSUME) { + ClientboundSetEntityDataPacket packet = new ClientboundSetEntityDataPacket( + player.getEntityId(), List.of(new DataValue(8, EntityDataSerializers.BYTE, (byte)(hand == EquipmentSlot.HAND ? 1 : 3))) + ); + NetworkUtils.send(player.getUniqueId(), packet); + if (nmsStack.getItem() instanceof InstrumentItem instrumentItem) { + Optional> optional = ReflectionUtils.call(instrumentItem, NMSMethods.INSTRUMENT_ITEM_getInstrument, nmsStack); + optional.ifPresent( + instrumentHolder -> { + Instrument instrument = (Instrument)instrumentHolder.value(); + Holder soundEvent = instrument.soundEvent(); + float f = instrument.range() / 16.0F; + RandomSource random = ReflectionUtils.get(nmsPlayer.level(), NMSFields.LEVEL_soundSeedGenerator); + ClientboundSoundEntityPacket soundPacket = new ClientboundSoundEntityPacket( + soundEvent, SoundSource.RECORDS, nmsPlayer, f, 1.0F, random.nextLong() + ); + NetworkUtils.send(player.getUniqueId(), soundPacket); + } + ); + } + } + } + ); + } + + @Override + public float getYRot(Entity entity) { + return EntityUtils.nms(entity).getYRot(); + } + + @Override + public float getYHeadRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.getYHeadRot() : nms.getYRot(); + } + + @Override + public float getXHeadRot(Entity entity) { + return EntityUtils.nms(entity).getXRot(); + } + + @Override + public float getYBodyRot(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms instanceof LivingEntity livingEntity ? livingEntity.yBodyRot : nms.getYRot(); + } + + @Override + public void setYRot(Entity entity, float angle) { + EntityUtils.nms(entity).setYRot(angle); + } + + @Override + public void setYHeadRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYHeadRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void setXHeadRot(Entity entity, float angle) { + EntityUtils.nms(entity).setXRot(angle); + } + + @Override + public void setYBodyRot(Entity entity, float angle) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms instanceof LivingEntity livingEntity) { + livingEntity.setYBodyRot(angle); + } else { + nms.setYRot(angle); + } + } + + @Override + public void move(Entity entity, double x, double y, double z) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + nms.move(MoverType.SELF, new Vec3(x, y, z)); + } + + @Override + public boolean isWalking(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + if (nms.tickCount < 1) { + return false; + } else { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + } + + @Override + public boolean isStrafing(Entity entity) { + return false; + } + + @Override + public boolean isJumping(Entity entity) { + if (JUMPING_GETTER != null && EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + try { + return (boolean)JUMPING_GETTER.invokeExact((LivingEntity)livingEntity); + } catch (Throwable var4) { + var4.printStackTrace(); + } + } + + return false; + } + + @Override + public boolean isFlying(Entity entity) { + return false; + } + + @Override + public float getHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getHealth() : 20.0F; + } + + @Override + public float getMaxHealth(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity livingEntity ? livingEntity.getMaxHealth() : 20.0F; + } + + @Override + public Vector3f getPivotOffset(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityTypes.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 offset = ReflectionUtils.call( + nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, nmsEntity.getDimensions(Pose.STANDING), 1.0F + ); + Vec3 offset2 = this.dummyCloud.getPassengerRidingPosition(this.dummyCloud); + return offset == null ? new Vector3f() : offset.add(offset2).toVector3f(); + } + + @Override + public Float getCameraEyeHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + return nmsEntity.getDimensions(Pose.STANDING).eyeHeight(); + } + + @Override + public Float getCameraPivotHeight(Entity entity) { + net.minecraft.world.entity.Entity nmsEntity = EntityUtils.nms(entity); + EntityDimensions dimensions = nmsEntity.getDimensions(nmsEntity.getPose()); + if (this.dummyCloud == null) { + this.dummyCloud = new AreaEffectCloud(EntityTypes.AREA_EFFECT_CLOUD, nmsEntity.level()); + } + + Vec3 attachment = ReflectionUtils.call(nmsEntity, NMSMethods.ENTITY_getPassengerAttachmentPoint, this.dummyCloud, dimensions, 1.0F); + return attachment == null ? null : (float)(dimensions.eyeHeight() - attachment.y); + } + + @Override + public boolean isRemoved(Entity entity) { + return EntityUtils.nms(entity).isRemoved(); + } + + @Override + public int getGlowColor(Entity entity) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + return nms.getTeamColor(); + } + + @Override + public Set getCollidableExemptions(Entity entity) { + return EntityUtils.nms(entity) instanceof LivingEntity living ? living.collidableExemptions : null; + } + + @Override + public Component getCustomName(Entity entity) { + net.minecraft.network.chat.Component name = EntityUtils.nms(entity).getCustomName(); + return name == null ? null : PaperAdventure.asAdventure(name); + } + + @Override + public void setDeathTick(Entity entity, int tick) { + if (EntityUtils.nms(entity) instanceof LivingEntity livingEntity) { + livingEntity.deathTime = tick; + } + } + + private static Int2ObjectMap getEntityMap(ChunkMap chunkMap) { + return chunkMap.entityMap; + } + + @Override + public com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity wrapTrackedEntity(Entity entity) { + ServerLevel level = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap map = getEntityMap(level.getChunkSource().chunkMap); + if (map == null) { + return new TempTrackedEntity(entity); + } else { + int entityId = entity.getEntityId(); + TrackedEntity tracker = (TrackedEntity)map.get(entityId); + return (com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity)(tracker == null + ? new TempTrackedEntity(entity) + : new TrackedEntityImpl(entity, () -> { + ServerLevel lvl = ((CraftWorld)entity.getWorld()).getHandle(); + Int2ObjectMap m = getEntityMap(lvl.getChunkSource().chunkMap); + return m == null ? null : (TrackedEntity)m.get(entity.getEntityId()); + }, tracker)); + } + } + + @Override + public boolean isGlowing(Entity entity) { + return EntityUtils.nms(entity).getSharedFlag(6); + } + + @Override + public boolean isVisualFire(Entity entity) { + return EntityUtils.nms(entity).getSharedFlag(0); + } + + @Override + public int getFireTicks(Entity entity) { + return this.isVisualFire(entity) ? 1 : 0; + } + + @Override + public BoundingBox getBoundingBox(Entity entity) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + return new BoundingBox(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public void getBoundingBox(Entity entity, BoundingBox dest) { + AABB nms = EntityUtils.nms(entity).getBoundingBox(); + dest.resize(nms.minX, nms.minY, nms.minZ, nms.maxX, nms.maxY, nms.maxZ); + } + + @Override + public void getLocation(Entity entity, Location location) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + Vec3 pos = nms.position(); + location.setWorld(nms.level().getWorld()); + location.setX(pos.x); + location.setY(pos.y); + location.setZ(pos.z); + location.setYaw(nms.getYRot()); + location.setPitch(nms.getXRot()); + } + + @Override + public boolean shouldCull(Player player, Location eyePosition, BoundingBox box) { + CraftWorld world = (CraftWorld)player.getWorld(); + Vec3 start = CraftLocation.toVec3(eyePosition); + if (!(box.getWidthX() >= this.forceRenderWidth) && !(box.getWidthZ() >= this.forceRenderWidth) && !(box.getHeight() >= this.forceRenderHeight)) { + int minX = Mth.floor(box.getMinX()); + int minY = Mth.floor(box.getMinY()); + int minZ = Mth.floor(box.getMinZ()); + int maxX = Mth.ceil(box.getMaxX()) - 1; + int maxY = Mth.ceil(box.getMaxY()) - 1; + int maxZ = Mth.ceil(box.getMaxZ()) - 1; + EntityHandler.BoxRelToCam relX = EntityHandler.BoxRelToCam.from(minX, maxX, Mth.floor(start.x)); + EntityHandler.BoxRelToCam relY = EntityHandler.BoxRelToCam.from(minY, maxY, Mth.floor(start.y)); + EntityHandler.BoxRelToCam relZ = EntityHandler.BoxRelToCam.from(minZ, maxZ, Mth.floor(start.z)); + if (relX == EntityHandler.BoxRelToCam.INSIDE && relY == EntityHandler.BoxRelToCam.INSIDE && relZ == EntityHandler.BoxRelToCam.INSIDE) { + return false; + } else { + if (DebugToggle.isDebugging(DebugToggle.SHOW_CULL_POINTS)) { + EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> { + world.spawnParticle(Particle.DUST, x, y, z, 1, new DustOptions(Color.RED, 0.2F)); + return false; + }); + } + + return !EntityHandler.sweepCullPoints(minX, minY, minZ, maxX, maxY, maxZ, relX, relY, relZ, (x, y, z) -> isVisible(world, start, new Vec3(x, y, z))); + } + } else { + return false; + } + } + + private static boolean isVisible(CraftWorld world, Vec3 startPos, Vec3 endPos) { + if (ServerInfo.IS_FOLIA && !Bukkit.isPrimaryThread()) { + return true; + } else if (!usePaperClipMethod) { + return OcclusionClipContext.isClear(world.getHandle(), startPos, endPos); + } else { + BlockHitResult nmsHitResult = world.getHandle().clip(new OcclusionClipContext(startPos, endPos)); + return nmsHitResult.getType() == Type.MISS; + } + } + + @Override + public void readEntityState(Entity entity, EntityState state) { + net.minecraft.world.entity.Entity nms = EntityUtils.nms(entity); + state.yRot = nms.getYRot(); + state.xHeadRot = nms.getXRot(); + if (nms instanceof LivingEntity living) { + state.yHeadRot = living.getYHeadRot(); + state.yBodyRot = living.yBodyRot; + state.health = living.getHealth(); + } else { + state.yHeadRot = state.yRot; + state.yBodyRot = state.yRot; + state.health = 20.0F; + } + + boolean walking = false; + if (nms.tickCount >= 1) { + double dX = nms.getX() - nms.xOld; + double dZ = nms.getZ() - nms.zOld; + walking = dX * dX + dZ * dZ > 2.5000003E-7F; + } + + state.walking = walking; + state.strafing = false; + state.flying = false; + state.removed = nms.isRemoved(); + state.jumping = this.isJumping(entity); + state.glowing = this.isGlowing(entity); + state.onFire = this.isVisualFire(entity); + this.getBoundingBox(entity, state.boundingBox); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityMetadataID.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityMetadataID.java new file mode 100644 index 0000000..015d0ca --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityMetadataID.java @@ -0,0 +1,37 @@ +package com.ticxo.modelengine.v26_3.entity; + +public class EntityMetadataID { + public static final int ENTITY_SHARED_DATA = 0; + public static final int ENTITY_AIR = 1; + public static final int ENTITY_CUSTOM_NAME = 2; + public static final int ENTITY_CUSTOM_NAME_VISIBLE = 3; + public static final int INTERACTION_WIDTH = 8; + public static final int INTERACTION_HEIGHT = 9; + public static final int INTERACTION_RESPONSE = 10; + public static final int DISPLAY_INTERPOLATION_DELAY = 8; + public static final int DISPLAY_TRANSFORM_DURATION = 9; + public static final int DISPLAY_POS_ROT_DURATION = 10; + public static final int DISPLAY_TRANSLATION = 11; + public static final int DISPLAY_SCALE = 12; + public static final int DISPLAY_ROTATION_LEFT = 13; + public static final int DISPLAY_ROTATION_RIGHT = 14; + public static final int DISPLAY_BILLBOARD = 15; + public static final int DISPLAY_BRIGHTNESS = 16; + public static final int DISPLAY_VIEW_RANGE = 17; + public static final int DISPLAY_SHADOW_RADIUS = 18; + public static final int DISPLAY_WIDTH = 20; + public static final int DISPLAY_HEIGHT = 21; + public static final int DISPLAY_GLOW_COLOR = 22; + public static final int ITEM_DISPLAY_ITEM = 23; + public static final int ITEM_DISPLAY_TYPE = 24; + public static final int TEXT_DISPLAY_TEXT = 23; + public static final int TEXT_LINE_WIDTH = 24; + public static final int TEXT_DISPLAY_BACKGROUND = 25; + public static final int TEXT_DISPLAY_OPACITY = 26; + public static final int TEXT_DISPLAY_OPTIONS = 27; + public static final int AREA_EFFECT_CLOUD_RADIUS = 8; + public static final int LIVING_ENTITY_HAND_DATA = 8; + public static final int LIVING_ENTITY_HEALTH = 9; + public static final int ARMOR_STAND_SHARED_DATA = 15; + public static final int SLIME_SIZE = 18; +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityUtils.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityUtils.java new file mode 100644 index 0000000..c40e422 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/EntityUtils.java @@ -0,0 +1,33 @@ +package com.ticxo.modelengine.v26_3.entity; + +import java.util.List; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.Entity; +import org.bukkit.craftbukkit.entity.CraftEntity; + +public class EntityUtils { + public static final List> DEFAULT_AREA_EFFECT_CLOUD_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(8, EntityDataSerializers.FLOAT, 0.0F) + ); + public static final List> DEFAULT_PIVOT_DISPLAY_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(10, EntityDataSerializers.INT, 1) + ); + public static final List> DEFAULT_SLIME_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(18, EntityDataSerializers.INT, 2) + ); + public static final List> DEFAULT_BAT_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE) + ); + public static final List> DEFAULT_ARMOR_STAND_DATA = List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(1, EntityDataSerializers.INT, Integer.MAX_VALUE), + new DataValue(15, EntityDataSerializers.BYTE, (byte)16) + ); + + public static Entity nms(org.bukkit.entity.Entity entity) { + return ((CraftEntity)entity).getHandleRaw(); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/OcclusionClipContext.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/OcclusionClipContext.java new file mode 100644 index 0000000..3695fc3 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/OcclusionClipContext.java @@ -0,0 +1,116 @@ +package com.ticxo.modelengine.v26_3.entity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; + +public class OcclusionClipContext extends ClipContext { + public OcclusionClipContext(Vec3 start, Vec3 end) { + super(start, end, Block.VISUAL, Fluid.NONE, (Entity)null); + } + + public VoxelShape getBlockShape(BlockState state, BlockGetter world, BlockPos pos) { + return occlusionShape(state, world, pos); + } + + private static VoxelShape occlusionShape(BlockState state, BlockGetter world, BlockPos pos) { + return state.canOcclude() && state.getOcclusionShape() == Shapes.block() ? Shapes.block() : Shapes.empty(); + } + + static boolean isClear(Level level, Vec3 from, Vec3 to) { + if (from.equals(to)) { + return true; + } else { + double toX = Mth.lerp(-1.0E-7, to.x, from.x); + double toY = Mth.lerp(-1.0E-7, to.y, from.y); + double toZ = Mth.lerp(-1.0E-7, to.z, from.z); + double fromX = Mth.lerp(-1.0E-7, from.x, to.x); + double fromY = Mth.lerp(-1.0E-7, from.y, to.y); + double fromZ = Mth.lerp(-1.0E-7, from.z, to.z); + int x = Mth.floor(fromX); + int y = Mth.floor(fromY); + int z = Mth.floor(fromZ); + double dx = toX - fromX; + double dy = toY - fromY; + double dz = toZ - fromZ; + int signX = Mth.sign(dx); + int signY = Mth.sign(dy); + int signZ = Mth.sign(dz); + double tDeltaX = signX == 0 ? Double.MAX_VALUE : signX / dx; + double tDeltaY = signY == 0 ? Double.MAX_VALUE : signY / dy; + double tDeltaZ = signZ == 0 ? Double.MAX_VALUE : signZ / dz; + double tX = tDeltaX * (signX > 0 ? 1.0 - Mth.frac(fromX) : Mth.frac(fromX)); + double tY = tDeltaY * (signY > 0 ? 1.0 - Mth.frac(fromY) : Mth.frac(fromY)); + double tZ = tDeltaZ * (signZ > 0 ? 1.0 - Mth.frac(fromZ) : Mth.frac(fromZ)); + MutableBlockPos pos = new MutableBlockPos(x, y, z); + ChunkAccess chunk = null; + int chunkX = 0; + int chunkZ = 0; + + while (true) { + pos.set(x, y, z); + BlockState state; + if (level.captureTreeGeneration) { + state = level.getBlockStateIfLoaded(pos); + } else if (level.isOutsideBuildHeight(pos)) { + state = Blocks.VOID_AIR.defaultBlockState(); + } else { + if (chunk == null || x >> 4 != chunkX || z >> 4 != chunkZ) { + chunkX = x >> 4; + chunkZ = z >> 4; + chunk = level.getChunkIfLoadedImmediately(chunkX, chunkZ); + } + + state = chunk == null ? null : chunk.getBlockState(pos); + } + + if (state == null) { + return true; + } + + if (!state.isAir()) { + VoxelShape shape = occlusionShape(state, level, pos); + if (!shape.isEmpty()) { + BlockHitResult hit = level.clipWithInteractionOverride(from, to, pos, shape, state); + if (hit != null && from.distanceToSqr(hit.getLocation()) <= Double.MAX_VALUE) { + return false; + } + } + } + + if (!(tX <= 1.0) && !(tY <= 1.0) && !(tZ <= 1.0)) { + return true; + } + + if (tX < tY) { + if (tX < tZ) { + x += signX; + tX += tDeltaX; + } else { + z += signZ; + tZ += tDeltaZ; + } + } else if (tY < tZ) { + y += signY; + tY += tDeltaY; + } else { + z += signZ; + tZ += tDeltaZ; + } + } + } + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/TrackedEntityImpl.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/TrackedEntityImpl.java new file mode 100644 index 0000000..b4154fa --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/TrackedEntityImpl.java @@ -0,0 +1,333 @@ +package com.ticxo.modelengine.v26_3.entity; + +import com.google.common.collect.Sets; +import com.ticxo.modelengine.api.ServerInfo; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v26_3.NMSFields; +import com.ticxo.modelengine.v26_3.NMSMethods; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Predicate; +import java.util.function.Supplier; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ChunkMap.TrackedEntity; +import net.minecraft.server.network.ServerPlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class TrackedEntityImpl implements com.ticxo.modelengine.api.nms.entity.wrapper.TrackedEntity { + private final Entity entity; + private final Supplier trackedEntitySupplier; + private final Set forcedPairing = Sets.newConcurrentHashSet(); + private final Set forcedRemove = Sets.newConcurrentHashSet(); + private Predicate playerPredicate = DEFAULT_PREDICATE; + @NotNull + private TrackedEntity lastTrackedEntity; + private static final int RECONCILE_INTERVAL = 20; + private Object[] lastSeenBy; + private volatile boolean viewersDirty = true; + private volatile boolean mayHaveForced; + private int ticksSinceReconcile; + private final int initialBaseRange; + + public TrackedEntityImpl(Entity entity, Supplier trackedEntitySupplier, @NotNull TrackedEntity lastTrackedEntity) { + this.entity = entity; + this.trackedEntitySupplier = trackedEntitySupplier; + this.lastTrackedEntity = lastTrackedEntity; + this.initialBaseRange = this.getBaseRange(); + } + + @Override + public int getInitialBaseRange() { + return this.initialBaseRange; + } + + @Override + public int getBaseRange() { + Integer range = ReflectionUtils.get(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve base range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public void setBaseRange(int range) { + ReflectionUtils.set(this.getTrackedEntity(), NMSFields.TRACKED_ENTITY_range, range); + } + + @Override + public int getEffectiveRange() { + Integer range = ReflectionUtils.call(this.getTrackedEntity(), NMSMethods.TRACKED_ENTITY_getEffectiveRange); + if (range == null) { + throw new NullPointerException(String.format("Unable to retrieve range of entity with UUID %s.", this.entity.getUniqueId())); + } else { + return range; + } + } + + @Override + public Set getTrackedPlayer() { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + Set tracked = this.entity.getTrackedPlayers(); + HashSet set = new HashSet<>(Math.max(8, (int)((tracked.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (Player player : tracked) { + if (this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null && this.playerPredicate.test(playerx) && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + set.add(playerx.getUniqueId()); + } + } + + return set; + } + } + + @Override + public Set getTrackedPlayer(Predicate predicate) { + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + Set tracked = this.entity.getTrackedPlayers(); + HashSet set = new HashSet<>(Math.max(8, (int)((tracked.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (Player player : tracked) { + if (predicate.test(player) && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + set.add(player.getUniqueId()); + } + } + + return set; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + HashSet set = new HashSet<>(Math.max(8, (int)((seenBy.size() + (hasForced ? this.forcedPairing.size() : 0)) / 0.75F) + 1)); + if (hasForced) { + set.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null + && predicate.test(playerx) + && this.playerPredicate.test(playerx) + && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + set.add(playerx.getUniqueId()); + } + } + + return set; + } + } + + @Override + public Set getTrackedPlayer(Predicate predicate, Set dest) { + dest.clear(); + boolean hasForced = !this.forcedPairing.isEmpty(); + boolean hasRemoved = !this.forcedRemove.isEmpty(); + if (ServerInfo.IS_FOLIA) { + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (Player player : this.entity.getTrackedPlayers()) { + if (predicate.test(player) && this.playerPredicate.test(player) && (!hasRemoved || !this.forcedRemove.contains(player.getUniqueId()))) { + dest.add(player.getUniqueId()); + } + } + + return dest; + } else { + Set seenBy = this.getTrackedEntity().seenBy; + if (hasForced) { + dest.addAll(this.forcedPairing); + } + + for (ServerPlayerConnection connection : seenBy) { + Player playerx = connection.getPlayer().getBukkitEntity(); + if (playerx != null + && predicate.test(playerx) + && this.playerPredicate.test(playerx) + && (!hasRemoved || !this.forcedRemove.contains(playerx.getUniqueId()))) { + dest.add(playerx.getUniqueId()); + } + } + + return dest; + } + } + + @Override + public boolean isViewerSetUnchanged() { + if (ServerInfo.IS_FOLIA + || this.mayHaveForced && (!this.forcedPairing.isEmpty() || !this.forcedRemove.isEmpty()) + || this.playerPredicate != DEFAULT_PREDICATE) { + this.lastSeenBy = null; + this.viewersDirty = true; + return false; + } else if (!this.viewersDirty && ++this.ticksSinceReconcile < 20) { + return true; + } else { + this.viewersDirty = false; + this.ticksSinceReconcile = 0; + return this.snapshotUnchanged(this.getTrackedEntity().seenBy); + } + } + + @Override + public void markViewersDirty() { + this.viewersDirty = true; + } + + private boolean snapshotUnchanged(Collection viewers) { + int size = viewers.size(); + Object[] previous = this.lastSeenBy; + if (previous != null && previous.length == size) { + int index = 0; + boolean same = true; + + for (Object viewer : viewers) { + if (index >= size || previous[index] != viewer) { + same = false; + break; + } + + index++; + } + + if (same && index == size) { + return true; + } + } + + Object[] snapshot = new Object[size]; + int index = 0; + + for (Object viewer : viewers) { + if (index >= size) { + break; + } + + snapshot[index++] = viewer; + } + + this.lastSeenBy = index == size ? snapshot : Arrays.copyOf(snapshot, index); + return false; + } + + @Override + public void sendPairingData(Player player) { + if (player != null) { + ServerPlayer nms = ((CraftPlayer)player).getHandle(); + this.getTrackedEntity().serverEntity.sendPairingData(nms, packet -> NetworkUtils.send(player.getUniqueId(), packet)); + } + } + + @Override + public void broadcastSpawn() { + for (UUID player : this.getTrackedPlayer()) { + this.sendPairingData(Bukkit.getPlayer(player)); + } + } + + @Override + public void broadcastRemove() { + this.getTrackedEntity().broadcastRemoved(); + } + + @Override + public void addForcedPairing(UUID uuid) { + this.mayHaveForced = true; + this.forcedPairing.add(uuid); + this.removeForcedHidden(uuid); + } + + @Override + public void removeForcedPairing(UUID uuid) { + this.forcedPairing.remove(uuid); + } + + @Override + public void clearForcedPairing() { + this.forcedPairing.clear(); + } + + @Override + public void addForcedHidden(UUID uuid) { + this.mayHaveForced = true; + this.forcedRemove.add(uuid); + this.removeForcedPairing(uuid); + } + + @Override + public void removeForcedHidden(UUID uuid) { + this.forcedRemove.remove(uuid); + } + + @Override + public void clearForcedHidden() { + this.forcedRemove.clear(); + } + + @NotNull + private TrackedEntity getTrackedEntity() { + TrackedEntity trackedEntity = this.trackedEntitySupplier.get(); + if (trackedEntity != null && this.lastTrackedEntity != trackedEntity) { + this.syncInstance(trackedEntity); + this.lastTrackedEntity = trackedEntity; + } + + return this.lastTrackedEntity; + } + + private void syncInstance(TrackedEntity target) { + Integer range = ReflectionUtils.get(this.lastTrackedEntity, NMSFields.TRACKED_ENTITY_range); + if (range != null) { + ReflectionUtils.set(target, NMSFields.TRACKED_ENTITY_range, range); + } + } + + @Override + public Entity getEntity() { + return this.entity; + } + + @Override + public Predicate getPlayerPredicate() { + return this.playerPredicate; + } + + @Override + public void setPlayerPredicate(Predicate playerPredicate) { + this.playerPredicate = playerPredicate; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/BodyRotationControlWrapper.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/BodyRotationControlWrapper.java new file mode 100644 index 0000000..d0c76db --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/BodyRotationControlWrapper.java @@ -0,0 +1,233 @@ +package com.ticxo.modelengine.v26_3.entity.controller; + +import com.ticxo.modelengine.api.nms.entity.wrapper.BodyRotationController; +import com.ticxo.modelengine.api.utils.math.TMath; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.BodyRotationControl; + +public class BodyRotationControlWrapper extends BodyRotationControl implements BodyRotationController { + private final Mob mob; + private boolean isHeadClampUneven; + private boolean isBodyClampUneven; + private float maxHeadAngle; + private float maxBodyAngle; + private float minHeadAngle; + private float minBodyAngle; + private boolean playerMode; + private float stableAngle = 15.0F; + private int rotationDelay = 10; + private int rotationDuration = 10; + private int headStableTime; + private float lastStableYHeadRot; + + public BodyRotationControlWrapper(Mob mob) { + super(mob); + this.mob = mob; + this.maxHeadAngle = mob.getMaxHeadYRot(); + this.maxBodyAngle = mob.getMaxHeadYRot(); + this.minHeadAngle = -this.maxHeadAngle; + this.minBodyAngle = -this.maxBodyAngle; + } + + public void clientTick() { + if (!this.getMob().isDeadOrDying()) { + if (this.isMoving()) { + this.mob.yBodyRot = this.mob.getYRot(); + this.rotateHeadIfNecessary(); + this.lastStableYHeadRot = this.mob.yHeadRot; + this.headStableTime = 0; + } else if (this.notCarryingMobPassengers()) { + if (Math.abs(this.mob.yHeadRot - this.lastStableYHeadRot) > this.stableAngle) { + this.headStableTime = 0; + this.lastStableYHeadRot = this.mob.yHeadRot; + this.rotateBodyIfNecessary(); + } else if (!this.playerMode) { + this.headStableTime++; + if (this.headStableTime > this.rotationDelay) { + this.rotateHeadTowardsFront(); + } + } + } + } + } + + @Override + public float getYHeadRot() { + return this.mob.yHeadRot; + } + + @Override + public void setYHeadRot(float rot) { + this.mob.yHeadRot = rot; + } + + @Override + public float getXHeadRot() { + return this.mob.getXRot(); + } + + @Override + public void setXHeadRot(float rot) { + this.mob.setXRot(rot); + } + + @Override + public float getYBodyRot() { + return this.mob.yBodyRot; + } + + @Override + public void setYBodyRot(float rot) { + this.mob.yBodyRot = rot; + } + + private void rotateBodyIfNecessary() { + this.mob.yBodyRot = TMath.rotateIfNecessary( + this.mob.yBodyRot, this.mob.yHeadRot, this.isBodyClampUneven ? this.minBodyAngle : -this.maxBodyAngle, this.maxBodyAngle + ); + } + + private void rotateHeadIfNecessary() { + this.mob.yHeadRot = TMath.rotateIfNecessary( + this.mob.yHeadRot, this.mob.yBodyRot, this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle, this.maxHeadAngle + ); + } + + private void rotateHeadTowardsFront() { + float ratio = (float)(this.headStableTime - this.rotationDelay) / this.rotationDuration; + float clampedRatio = TMath.clamp(ratio, 0.0F, 1.0F); + float maxClamp = this.maxHeadAngle * (1.0F - clampedRatio); + float minClamp = (this.isHeadClampUneven ? this.minHeadAngle : -this.maxHeadAngle) * (1.0F - clampedRatio); + this.mob.yBodyRot = TMath.rotateIfNecessary(this.mob.yBodyRot, this.mob.yHeadRot, minClamp, maxClamp); + } + + private boolean notCarryingMobPassengers() { + return !(this.mob.getFirstPassenger() instanceof Mob); + } + + private boolean isMoving() { + double dX = this.mob.getX() - this.mob.xo; + double dZ = this.mob.getZ() - this.mob.zo; + return dX * dX + dZ * dZ > 2.5000003E-7F; + } + + public Mob getMob() { + return this.mob; + } + + @Override + public boolean isHeadClampUneven() { + return this.isHeadClampUneven; + } + + @Override + public boolean isBodyClampUneven() { + return this.isBodyClampUneven; + } + + @Override + public float getMaxHeadAngle() { + return this.maxHeadAngle; + } + + @Override + public float getMaxBodyAngle() { + return this.maxBodyAngle; + } + + @Override + public float getMinHeadAngle() { + return this.minHeadAngle; + } + + @Override + public float getMinBodyAngle() { + return this.minBodyAngle; + } + + @Override + public boolean isPlayerMode() { + return this.playerMode; + } + + @Override + public float getStableAngle() { + return this.stableAngle; + } + + @Override + public int getRotationDelay() { + return this.rotationDelay; + } + + @Override + public int getRotationDuration() { + return this.rotationDuration; + } + + public int getHeadStableTime() { + return this.headStableTime; + } + + public float getLastStableYHeadRot() { + return this.lastStableYHeadRot; + } + + @Override + public void setHeadClampUneven(boolean isHeadClampUneven) { + this.isHeadClampUneven = isHeadClampUneven; + } + + @Override + public void setBodyClampUneven(boolean isBodyClampUneven) { + this.isBodyClampUneven = isBodyClampUneven; + } + + @Override + public void setMaxHeadAngle(float maxHeadAngle) { + this.maxHeadAngle = maxHeadAngle; + } + + @Override + public void setMaxBodyAngle(float maxBodyAngle) { + this.maxBodyAngle = maxBodyAngle; + } + + @Override + public void setMinHeadAngle(float minHeadAngle) { + this.minHeadAngle = minHeadAngle; + } + + @Override + public void setMinBodyAngle(float minBodyAngle) { + this.minBodyAngle = minBodyAngle; + } + + @Override + public void setPlayerMode(boolean playerMode) { + this.playerMode = playerMode; + } + + @Override + public void setStableAngle(float stableAngle) { + this.stableAngle = stableAngle; + } + + @Override + public void setRotationDelay(int rotationDelay) { + this.rotationDelay = rotationDelay; + } + + @Override + public void setRotationDuration(int rotationDuration) { + this.rotationDuration = rotationDuration; + } + + public void setHeadStableTime(int headStableTime) { + this.headStableTime = headStableTime; + } + + public void setLastStableYHeadRot(float lastStableYHeadRot) { + this.lastStableYHeadRot = lastStableYHeadRot; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/LookControlWrapper.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/LookControlWrapper.java new file mode 100644 index 0000000..b72bf80 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/LookControlWrapper.java @@ -0,0 +1,145 @@ +package com.ticxo.modelengine.v26_3.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehaviorType; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.LookController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.control.LookControl; +import net.minecraft.world.phys.Vec3; + +public class LookControlWrapper extends LookControl implements LookController { + private final LookControl original; + private ModeledEntity modeledEntity; + private MovementOverride movementOverride; + + public LookControlWrapper(Mob mob, LookControl control) { + super(mob); + this.original = control; + } + + public void setLookAt(Vec3 var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0) { + this.original.setLookAt(var0); + } + + public void setLookAt(Entity var0, float var1, float var2) { + this.original.setLookAt(var0, var1, var2); + } + + public void setLookAt(double var0, double var2, double var4) { + this.original.setLookAt(var0, var2, var4); + } + + public void setLookAt(double var0, double var2, double var4, float var6, float var7) { + this.original.setLookAt(var0, var2, var4, var6, var7); + } + + public void tick() { + if (this.modeledEntity == null) { + this.modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + } + + BehaviorManager mountManager = this.getMainManager(); + if (mountManager != null && ((MountManager)mountManager).isControlled()) { + this.controlledTick(asMountManager(mountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateDirection(this, this.modeledEntity); + } else { + this.defaultTick(); + } + } + + protected & MountManager> void controlledTick(T manager) { + org.bukkit.entity.Entity driver = manager.getDriver(); + if (driver != null) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(driver.getUniqueId()); + if (controller != null) { + controller.updateDirection(this, manager.getActiveModel()); + return; + } + } + + this.defaultTick(); + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + public boolean isLookingAtTarget() { + return this.original.isLookingAtTarget(); + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + @Override + public void lookAt(double x, double y, double z) { + double dX = x - this.mob.getX(); + double dY = y - this.mob.getEyeY(); + double dZ = z - this.mob.getZ(); + double hMagnitude = Math.sqrt(dX * dX + dZ * dZ); + float pitch = (float)Math.toDegrees(Math.atan2(-dY, hMagnitude)); + float yaw = (float)Math.toDegrees(Math.atan2(-dX, dZ)); + this.setPitch(pitch); + this.setHeadYaw(yaw); + } + + @Override + public void setPitch(float pitch) { + this.mob.setXRot(pitch); + } + + @Override + public void setHeadYaw(float yaw) { + this.mob.setYRot(yaw); + this.mob.yHeadRot = yaw; + } + + @Override + public void setBodyYaw(float yaw) { + this.mob.yBodyRot = yaw; + } + + private & MountManager> T getMainManager() { + if (this.modeledEntity == null) { + return null; + } else { + return this.modeledEntity.getGlobalBehaviorData(BoneBehaviorTypes.MOUNT) instanceof MountData mountData + ? mountData.getMainMountManager() + : null; + } + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/MoveControlWrapper.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/MoveControlWrapper.java new file mode 100644 index 0000000..0d3ab4d --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/controller/MoveControlWrapper.java @@ -0,0 +1,272 @@ +package com.ticxo.modelengine.v26_3.entity.controller; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.animation.rootmotion.RootMotionDelta; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.behavior.GlobalBehaviorData; +import com.ticxo.modelengine.api.model.bone.manager.BehaviorManager; +import com.ticxo.modelengine.api.model.bone.manager.MountData; +import com.ticxo.modelengine.api.model.bone.manager.MountManager; +import com.ticxo.modelengine.api.model.bone.type.Mount; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MoveController; +import com.ticxo.modelengine.api.nms.entity.wrapper.MovementOverride; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_3.NMSFields; +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.ConcurrentLinkedQueue; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.ai.control.MoveControl; +import net.minecraft.world.phys.Vec3; +import org.apache.logging.log4j.util.TriConsumer; +import org.bukkit.Input; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class MoveControlWrapper extends MoveControl implements MoveController { + protected final MoveControl original; + protected final Queue runnables = new ConcurrentLinkedQueue<>(); + protected boolean isOnGround; + protected MovementOverride movementOverride; + + public MoveControlWrapper(Mob mob, MoveControl control) { + super(mob); + this.original = control; + } + + public boolean hasWanted() { + return this.original.hasWanted(); + } + + public double getSpeedModifier() { + return this.original.getSpeedModifier(); + } + + public void setWantedPosition(double x, double y, double z, double speed) { + this.original.setWantedPosition(x, y, z, speed); + } + + public void strafe(float forward, float sideways) { + this.original.strafe(forward, sideways); + } + + public void tick() { + this.isOnGround = this.mob.onGround(); + ModeledEntity modeledEntity = ModelEngineAPI.getModeledEntity(this.mob.getUUID()); + if (modeledEntity == null) { + this.defaultTick(); + } else { + GlobalBehaviorData mountData = modeledEntity.getMountData(); + BehaviorManager mainMountManager = mountData == null ? null : ((MountData)mountData).getMainMountManager(); + if (mainMountManager != null && ((MountManager)mainMountManager).isControlled()) { + this.mob.setOnGround(true); + this.disableWaterJumping(); + this.driverTick(asMountManager(mainMountManager)); + } else if (this.movementOverride != null) { + this.movementOverride.updateMovement(this, modeledEntity); + } else { + this.defaultTick(); + } + + this.passengerTick(modeledEntity, asMountManager(mainMountManager)); + + while (!this.runnables.isEmpty()) { + this.runnables.poll().run(); + } + + Vector mobMotion = this.toVector(); + RootMotionDelta rootMotion = modeledEntity.getRootMotionHandler().calculateRootMotion(mobMotion); + this.fromVector(mobMotion); + if (rootMotion != null) { + Vector velocity = rootMotion.delta(); + if (!velocity.isZero() || !rootMotion.onGround()) { + this.nullifyFallDistance(); + if (!TMath.isSimilar((float)velocity.getY(), 0.0F) || !rootMotion.onGround()) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().multiply(1.0, 0.0, 1.0)); + } + + this.mob.move(MoverType.SELF, new Vec3(velocity.getX(), velocity.getY(), velocity.getZ())); + } + } + } + } + + public double getWantedX() { + return this.original.getWantedX(); + } + + public double getWantedY() { + return this.original.getWantedY(); + } + + public double getWantedZ() { + return this.original.getWantedZ(); + } + + protected & MountManager> void driverTick(T manager) { + this.mob.setZza(0.0F); + this.mob.setXxa(0.0F); + this.updateRider(manager.getDriver(), manager.getActiveModel(), manager.getDriverBone(), MountController::updateDriverMovement); + } + + protected & MountManager> void passengerTick(ModeledEntity modeledEntity, T manager) { + for (ActiveModel activeModel : modeledEntity.getModels().values()) { + activeModel.getMountManager() + .ifPresent( + mountManager -> { + for (BoneBehavior seat : ((MountManager)mountManager).getSeats().values()) { + for (Entity passenger : ((Mount)seat).getPassengers()) { + this.updateRider(passenger, activeModel, (Mount)seat, MountController::updatePassengerMovement); + } + } + + if (mountManager != manager && ((MountManager)mountManager).isControlled()) { + this.updateRider( + ((MountManager)mountManager).getDriver(), + activeModel, + ((MountManager)mountManager).getDriverBone(), + MountController::updatePassengerMovement + ); + } + } + ); + } + } + + private void updateRider(Entity entity, ActiveModel activeModel, Mount mountBone, TriConsumer updateMethod) { + MountController controller = this.getController(entity.getUniqueId()); + if (controller != null) { + if (controller.getInput() == null) { + if (entity instanceof Player player) { + Input playerInput = player.getCurrentInput(); + controller.setInput( + new MountController.MountInput( + playerInput.isForward(), + playerInput.isBackward(), + playerInput.isLeft(), + playerInput.isRight(), + playerInput.isJump(), + playerInput.isSneak(), + playerInput.isSprint() + ) + ); + } else { + controller.setInput(new MountController.MountInput()); + } + } + + updateMethod.accept(controller, this, activeModel); + } + } + + @Override + public void defaultTick() { + this.original.tick(); + } + + private void disableWaterJumping() { + if (this.mob.isInWater()) { + ReflectionUtils.set(this.mob, NMSFields.LIVING_ENTITY_noJumpDelay, 1); + } + } + + @Override + public void move(float side, float up, float front, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + this.mob.setZza(front); + this.mob.setYya(up); + this.mob.setXxa(side); + } + + @Override + public void globalMove(float x, float y, float z, float speedModifier) { + float speed = this.getSpeed(); + this.mob.setSpeed(speed * speedModifier); + Vec3 vec = new Vec3(x, y, z).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private void fromVector(Vector vector) { + Vec3 vec = new Vec3(vector.getX(), vector.getY(), vector.getZ()).yRot(-this.mob.getYRot() * (float) (Math.PI / 180.0)); + this.mob.setXxa((float)vec.x); + this.mob.setYya((float)vec.y); + this.mob.setZza((float)vec.z); + } + + private Vector toVector() { + return new Vector( + Float.isNaN(this.mob.xxa) ? 0.0F : this.mob.xxa, Float.isNaN(this.mob.yya) ? 0.0F : this.mob.yya, Float.isNaN(this.mob.zza) ? 0.0F : this.mob.zza + ) + .rotateAroundY(this.mob.getYRot() * (float) (Math.PI / 180.0)); + } + + @Override + public void jump() { + this.mob.getJumpControl().jump(); + } + + @Override + public void setVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(x, y, z); + } + + @Override + public void addVelocity(double x, double y, double z) { + this.mob.setDeltaMovement(this.mob.getDeltaMovement().add(x, y, z)); + } + + @Override + public void nullifyFallDistance() { + this.mob.resetFallDistance(); + } + + @Override + public boolean isOnGround() { + return this.isOnGround; + } + + @Override + public boolean isInWater() { + return this.mob.isInWater(); + } + + @Override + public float getSpeed() { + return (float)this.mob.getAttributeValue(Attributes.MOVEMENT_SPEED); + } + + @Override + public Vector getVelocity() { + return CraftVector.toBukkit(this.mob.getDeltaMovement()); + } + + @Override + public void queuePostTick(Runnable runnable) { + this.runnables.add(runnable); + } + + private MountController getController(UUID uuid) { + return ModelEngineAPI.getMountPairManager().getController(uuid); + } + + @Override + public void setMovementOverride(MovementOverride movementOverride) { + this.movementOverride = movementOverride; + } + + @SuppressWarnings("unchecked") + private static & MountManager> M asMountManager(Object manager) { + return (M)manager; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/hitbox/HitboxEntityImpl.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/hitbox/HitboxEntityImpl.java new file mode 100644 index 0000000..9671853 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/hitbox/HitboxEntityImpl.java @@ -0,0 +1,288 @@ +package com.ticxo.modelengine.v26_3.entity.hitbox; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.model.bone.type.SubHitbox; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import com.ticxo.modelengine.api.utils.promise.Promise; +import com.ticxo.modelengine.v26_3.NMSFields; +import com.ticxo.modelengine.v26_3.entity.EntityUtils; +import java.util.UUID; +import net.minecraft.core.NonNullList; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Entity.RemovalReason; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.util.CraftLocation; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; +import org.jspecify.annotations.NonNull; + +public class HitboxEntityImpl extends LivingEntity implements HitboxEntity { + private final NonNullList handItems = NonNullList.withSize(2, ItemStack.EMPTY); + private final NonNullList armorItems = NonNullList.withSize(4, ItemStack.EMPTY); + private final ModelBone bone; + private final SubHitbox subHitbox; + private OBB obb; + private volatile Vector3f location; + private boolean markRemoved; + + public HitboxEntityImpl(Level world, @NotNull ModelBone bone, @NotNull SubHitbox subHitbox) { + super(EntityTypes.SILVERFISH, world); + this.bone = bone; + this.subHitbox = subHitbox; + this.setPermanentlyInvulnerable(true); + this.setNoGravity(true); + this.noPhysics = true; + } + + public boolean canBeHitByProjectile() { + return this.subHitbox.isCanBeHitByProjectile(); + } + + @NotNull + public HumanoidArm getMainArm() { + return HumanoidArm.RIGHT; + } + + public boolean isInvisible() { + return true; + } + + public void push(@NotNull Entity entity) { + } + + @NotNull + protected AABB makeBoundingBox(Vec3 position) { + if (this.subHitbox == null) { + return super.makeBoundingBox(position); + } else { + Vector3f pos = this.subHitbox.getLocation(); + Vector3f dim = this.subHitbox.getDimension(); + if (this.subHitbox.isOBB()) { + float halfX = dim.x * 0.5F; + float halfY = dim.y * 0.5F; + float halfZ = dim.z * 0.5F; + Quaternionf rot = this.subHitbox.getRotation(); + float yaw = this.subHitbox.getYaw(); + this.obb = new OBB(pos.x - halfX, pos.y - halfY, pos.z - halfZ, pos.x + halfX, pos.y + halfY, pos.z + halfZ, rot, yaw); + return this.obb; + } else { + float halfX = dim.x * 0.5F; + float halfZ = dim.z * 0.5F; + return new AABB(pos.x - halfX, pos.y, pos.z - halfZ, pos.x + halfX, pos.y + dim.y, pos.z + halfZ); + } + } + } + + public void tick() { + if (this.markRemoved) { + this.discard(); + } else { + super.tick(); + if (this.bone == null || this.subHitbox == null) { + this.discard(); + } else if (!this.bone.getActiveModel().getModeledEntity().getBase().isAlive()) { + this.discard(); + } else { + Vector3f loc = this.location; + if (loc != null && loc.isFinite()) { + Vec3 vec = new Vec3(loc); + this.setPos(vec); + + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).setPos(vec); + } + } + } + } + } + + public boolean fireImmune() { + return true; + } + + protected void pushEntities() { + } + + protected void doPush(@NotNull Entity entity) { + } + + public void aiStep() { + } + + public boolean isPushable() { + return false; + } + + public boolean hurtServer(@NotNull ServerLevel world, @NotNull DamageSource source, float amount) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + EntityUtils.nms(entity).hurtServer(world, source, amount); + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return false; + } else { + BaseEntity baseEntity = this.bone.getActiveModel().getModeledEntity().getBase(); + CraftHumanEntity cause = source.getEntity() instanceof Player player ? player.getBukkitEntity() : null; + return baseEntity.hurt(this, cause, source, amount * this.subHitbox.getDamageMultiplier()); + } + } + + @NotNull + public InteractionResult interact(Player player, @NotNull InteractionHand hand, @NonNull Vec3 location) { + if (player.getBukkitEntity() instanceof org.bukkit.entity.Player craftPlayer) { + for (org.bukkit.entity.Entity entity : this.subHitbox.getBoundEntities().values()) { + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + craftPlayer, entity, new Vector(0, 0, 0), hand == InteractionHand.OFF_HAND ? EquipmentSlot.OFF_HAND : EquipmentSlot.HAND + ); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + EntityUtils.nms(entity).interact(player, hand, location); + } + } + } + + if (this.subHitbox.getDamageMultiplier() <= 1.0E-5F) { + return InteractionResult.PASS; + } else { + EntityHandler.InteractionResult result = this.bone + .getActiveModel() + .getModeledEntity() + .getBase() + .interact(this, player.getBukkitEntity(), hand == InteractionHand.MAIN_HAND ? EquipmentSlot.HAND : EquipmentSlot.OFF_HAND); + + return (InteractionResult)(switch (result) { + case SUCCESS -> InteractionResult.SUCCESS_SERVER; + case SUCCESS_NO_ITEM_USED -> InteractionResult.TRY_WITH_EMPTY_HAND; + case CONSUME -> InteractionResult.CONSUME; + case CONSUME_PARTIAL -> InteractionResult.SUCCESS; + case PASS -> InteractionResult.PASS; + case FAIL -> InteractionResult.FAIL; + }); + } + } + + public boolean shouldBeSaved() { + return false; + } + + @NotNull + public CraftLivingEntity getBukkitEntity() { + CraftLivingEntity bukkitEntity = (CraftLivingEntity)this.getBukkitEntityR(); + if (bukkitEntity == null) { + synchronized (this) { + bukkitEntity = new CraftLivingEntity(this.level().getCraftServer(), this); + this.setBukkitEntityR(bukkitEntity); + return bukkitEntity; + } + } else { + return bukkitEntity; + } + } + + private void setBukkitEntityR(CraftEntity craftEntity) { + ReflectionUtils.set(this, NMSFields.ENTITY_bukkitEntity, craftEntity); + } + + private CraftEntity getBukkitEntityR() { + return this.getBukkitEntityRaw(); + } + + protected int decreaseAirSupply(int air) { + return air; + } + + protected int increaseAirSupply(int air) { + return air; + } + + public void remove(@NotNull RemovalReason reason) { + super.remove(reason); + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + } + + @Override + public int getEntityId() { + return this.getId(); + } + + @Override + public UUID getUniqueId() { + return this.getUUID(); + } + + @Override + public void queueLocation(Vector3f location) { + this.location = location; + } + + @Override + public Location getLocation() { + return CraftLocation.toBukkit(this.position(), this.level().getWorld(), this.getBukkitYaw(), this.getXRot()); + } + + @Nullable + @Override + public OrientedBoundingBox getOrientedBoundingBox() { + return this.obb == null ? null : this.obb.getBukkitOBB(); + } + + @Override + public boolean isValid() { + return !this.isRemoved() && !this.markRemoved; + } + + @Override + public void markRemoved() { + if (!this.markRemoved) { + this.markRemoved = true; + ModelEngineAPI.setRenderCanceled(this.getId(), false); + ModelEngineAPI.getInteractionTracker().removeHitbox(this.getEntityId()); + + try { + Promise.start(this.getBukkitEntity()).thenRunSync(() -> { + if (!this.isRemoved()) { + this.discard(); + } + }); + } catch (Throwable var2) { + } + } + } + + @Override + public ModelBone getBone() { + return this.bone; + } + + @Override + public SubHitbox getSubHitbox() { + return this.subHitbox; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/hitbox/OBB.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/hitbox/OBB.java new file mode 100644 index 0000000..5801b3e --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/hitbox/OBB.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v26_3.entity.hitbox; + +import com.ticxo.modelengine.api.utils.math.OrientedBoundingBox; +import java.util.Optional; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class OBB extends AABB { + private final Quaternionf rotation; + private final float yaw; + private final OrientedBoundingBox bukkitOBB; + + public OBB(Vec3 cornerA, Vec3 cornerB, Quaternionf rotation, float yaw) { + this(cornerA.x, cornerA.y, cornerA.z, cornerB.x, cornerB.y, cornerB.z, rotation, yaw); + } + + public OBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, Quaternionf rotation, float yaw) { + super(minX, minY, minZ, maxX, maxY, maxZ); + this.rotation = rotation; + this.yaw = yaw; + this.bukkitOBB = new OrientedBoundingBox( + this.getCenter().toVector3f(), new Vector3f((float)this.getXsize(), (float)this.getYsize(), (float)this.getZsize()), rotation, yaw + ); + } + + public OBB makeOBBInstance(Vec3 position, Quaternionf rotation, float yaw) { + return new OBB(position.add(this.minX, this.minY, this.minZ), position.add(this.maxX, this.maxY, this.maxZ), rotation, yaw); + } + + @NotNull + public AABB inflate(double xInflate, double yInflate, double zInflate) { + double minX = this.minX - xInflate; + double minY = this.minY - yInflate; + double minZ = this.minZ - zInflate; + double maxX = this.maxX + xInflate; + double maxY = this.maxY + yInflate; + double maxZ = this.maxZ + zInflate; + return new OBB(minX, minY, minZ, maxX, maxY, maxZ, this.rotation, this.yaw); + } + + public boolean intersects(@NotNull AABB aabb) { + return aabb instanceof OBB obb ? this.intersects(obb) : super.intersects(aabb); + } + + public boolean intersects(OBB obb) { + return this.bukkitOBB.intersects(obb.bukkitOBB); + } + + public boolean intersects(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + OrientedBoundingBox obbB = new OrientedBoundingBox((float)minX, (float)minY, (float)minZ, (float)maxX, (float)maxY, (float)maxZ); + return this.bukkitOBB.intersects(obbB); + } + + public Optional clip(Vec3 from, Vec3 to) { + Quaternionf inverse = this.rotation.conjugate(new Quaternionf()); + Vec3 center = this.getCenter(); + float yaw = this.yaw * (float) (Math.PI / 180.0); + Vec3 rFrom = new Vec3(from.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Vec3 rTo = new Vec3(to.subtract(center).toVector3f().rotateY(-yaw).rotate(inverse)).add(center); + Optional result = super.clip(rFrom, rTo); + if (result.isEmpty()) { + return result; + } else { + Vec3 clip = new Vec3(result.get().subtract(center).toVector3f().rotate(this.rotation).rotateY(yaw)).add(center); + return Optional.of(clip); + } + } + + public String toString() { + return "OBB(rotation=" + this.getRotation() + ", yaw=" + this.getYaw() + ", bukkitOBB=" + this.getBukkitOBB() + ")"; + } + + public Quaternionf getRotation() { + return this.rotation; + } + + public float getYaw() { + return this.yaw; + } + + public OrientedBoundingBox getBukkitOBB() { + return this.bukkitOBB; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/AmphibiousNavigationWrapper.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/AmphibiousNavigationWrapper.java new file mode 100644 index 0000000..fd3dac4 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/AmphibiousNavigationWrapper.java @@ -0,0 +1,87 @@ +package com.ticxo.modelengine.v26_3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.AmphibiousPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class AmphibiousNavigationWrapper extends AmphibiousPathNavigation { + private final AmphibiousPathNavigation oldNav; + + public AmphibiousNavigationWrapper(Mob mob, AmphibiousPathNavigation oldNav) { + super(mob, mob.level()); + this.oldNav = oldNav; + this.setCanFloat(oldNav.canFloat()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } + + public boolean isStableDestination(BlockPos var0) { + return this.oldNav.isStableDestination(var0); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/FlyingNavigationWrapper.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/FlyingNavigationWrapper.java new file mode 100644 index 0000000..185cb94 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/FlyingNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v26_3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.FlyingPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class FlyingNavigationWrapper extends FlyingPathNavigation { + public FlyingNavigationWrapper(Mob mob, FlyingPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/GroundNavigationWrapper.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/GroundNavigationWrapper.java new file mode 100644 index 0000000..f7a2ba9 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/GroundNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v26_3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class GroundNavigationWrapper extends GroundPathNavigation { + public GroundNavigationWrapper(Mob mob, GroundPathNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/WallClimberNavigationWrapper.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/WallClimberNavigationWrapper.java new file mode 100644 index 0000000..bbb51c7 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/WallClimberNavigationWrapper.java @@ -0,0 +1,81 @@ +package com.ticxo.modelengine.v26_3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WallClimberNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WallClimberNavigationWrapper extends WallClimberNavigation { + public WallClimberNavigationWrapper(Mob mob, WallClimberNavigation oldNav) { + super(mob, mob.level()); + this.setCanFloat(oldNav.canFloat()); + oldNav.getNodeEvaluator().setCanOpenDoors(oldNav.getNodeEvaluator().canOpenDoors()); + oldNav.getNodeEvaluator().setCanPassDoors(oldNav.getNodeEvaluator().canPassDoors()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/WaterBoundNavigationWrapper.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/WaterBoundNavigationWrapper.java new file mode 100644 index 0000000..8392222 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/entity/navigation/WaterBoundNavigationWrapper.java @@ -0,0 +1,78 @@ +package com.ticxo.modelengine.v26_3.entity.navigation; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation; +import net.minecraft.world.level.pathfinder.Path; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; + +public class WaterBoundNavigationWrapper extends WaterBoundPathNavigation { + public WaterBoundNavigationWrapper(Mob mob) { + super(mob, mob.level()); + } + + public boolean moveTo(@Nullable Path newPath, double speed) { + if (!ModelEngineAPI.getConfigCache().isOverrideMoveTo()) { + return super.moveTo(newPath, speed); + } else { + if (newPath != null && !newPath.sameAs(this.path)) { + int closestNode = newPath.getNextNodeIndex(); + double distanceSqr = this.getNodeDistanceSquared(newPath.getNextEntityPos(this.mob)); + + for (int i = closestNode + 1; i < newPath.getNodeCount(); i++) { + double temp = this.getNodeDistanceSquared(newPath.getEntityPosAtNode(this.mob, i)); + if (temp < distanceSqr) { + distanceSqr = temp; + closestNode = i; + } + } + + newPath.setNextNodeIndex(closestNode); + } + + return super.moveTo(newPath, speed); + } + } + + private double getNodeDistanceSquared(Vec3 pos) { + double x = pos.x - this.mob.getX(); + double y = pos.y - this.mob.getY(); + double z = pos.z - this.mob.getZ(); + return x * x + y * y + z * z; + } + + protected void followThePath() { + Vec3 mobPosition = this.getTempMobPos(); + this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + double distX = Math.abs(this.mob.getX() - targetNodePosition.x); + double distY = Math.abs(this.mob.getY() - targetNodePosition.y); + double distZ = Math.abs(this.mob.getZ() - targetNodePosition.z); + boolean hasArrivedNode = distX < this.maxDistanceToWaypoint && distZ < this.maxDistanceToWaypoint && distY < 1.0; + boolean canAdvance = hasArrivedNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPosition); + if (canAdvance) { + this.path.advance(); + } + + this.doStuckDetection(mobPosition); + } + + private boolean shouldTargetNextNodeInDirection(Vec3 mobPosition) { + if (this.path.getNextNodeIndex() + 1 >= this.path.getNodeCount()) { + return false; + } else { + Vec3 targetNodePosition = this.path.getNextEntityPos(this.mob); + if (!mobPosition.closerThan(targetNodePosition, 2.0)) { + return false; + } else if (this.canMoveDirectly(mobPosition, this.path.getNextEntityPos(this.mob))) { + return true; + } else { + Vec3 nextNodePosition = this.path.getEntityPosAtNode(this.mob, this.path.getNextNodeIndex() + 1); + Vec3 nextNodeDir = nextNodePosition.subtract(targetNodePosition); + Vec3 mobDir = mobPosition.subtract(targetNodePosition); + return nextNodeDir.dot(mobDir) > 0.0; + } + } + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/ModelEngineChannelHandler.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/ModelEngineChannelHandler.java new file mode 100644 index 0000000..98086cd --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/ModelEngineChannelHandler.java @@ -0,0 +1,474 @@ +package com.ticxo.modelengine.v26_3.network; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.DynamicHitbox; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModelUpdaters; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.PivotOverride; +import com.ticxo.modelengine.api.model.PivotOverrideRegistry; +import com.ticxo.modelengine.api.model.bone.BoneBehaviorTypes; +import com.ticxo.modelengine.api.model.bone.behavior.BoneBehavior; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRenderer; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.mount.controller.MountController; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.network.CancelType; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import com.ticxo.modelengine.api.utils.data.tracker.CollectionDataTracker; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_3.NMSFields; +import com.ticxo.modelengine.v26_3.entity.EntityContainer; +import com.ticxo.modelengine.v26_3.network.patch.ServerboundAttackPacketWrapper; +import com.ticxo.modelengine.v26_3.network.patch.ServerboundInteractPacketWrapper; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_3.network.utils.PacketInterceptor; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import it.unimi.dsi.fastutil.Pair; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntList; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ServerboundPongPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundAttackPacket; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.PosRot; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class ModelEngineChannelHandler extends ChannelDuplexHandler { + private static final MethodHandle MOVE_ENTITY_ID = entityIdGetter(NMSFields.CLIENTBOUND_MOVE_ENTITY_PACKET_entityId); + private static final MethodHandle ROTATE_HEAD_ID = entityIdGetter(NMSFields.CLIENTBOUND_ROTATE_HEAD_PACKET_entityId); + private final Player player; + private final ServerPlayer serverPlayer; + private final ModelUpdaters updaters; + private final EntityHandler entityHandler; + private final ClientDesyncMonitor desyncMonitor; + private final PacketInterceptor writeInterceptors; + private final PacketInterceptor readInterceptors; + + private static MethodHandle entityIdGetter(NMSFields field) { + try { + return MethodHandles.lookup().unreflectGetter(ReflectionUtils.getField(field)); + } catch (IllegalAccessException var2) { + throw new ExceptionInInitializerError(var2); + } + } + + public ModelEngineChannelHandler(Player player, PipelineWrapper pipeline) { + this.player = player; + this.serverPlayer = ((CraftPlayer)player).getHandle(); + this.updaters = ModelEngineAPI.getAPI().getModelUpdaters(); + this.entityHandler = ModelEngineAPI.getEntityHandler(); + this.desyncMonitor = pipeline.getDesyncMonitor(); + this.writeInterceptors = new PacketInterceptor(); + this.writeInterceptors + .register(ClientboundAddEntityPacket.class, this::handleAddEntity) + .register(ClientboundRemoveEntitiesPacket.class, this::handleRemoveEntities) + .register(Pos.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(Rot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(PosRot.class, packet -> this.handleEntityId(packet, MOVE_ENTITY_ID)) + .register(ClientboundRotateHeadPacket.class, packet -> this.handleEntityId(packet, ROTATE_HEAD_ID)) + .register(ClientboundEntityEventPacket.class, this::handleEntityId) + .register(ClientboundSetEntityMotionPacket.class, this::handleEntityMotion) + .register(ClientboundTeleportEntityPacket.class, this::handleTeleportEntity) + .register(ClientboundEntityPositionSyncPacket.class, this::handlePositionSync) + .register(ClientboundAnimatePacket.class, this::handleAnimate) + .register(ClientboundSetEntityDataPacket.class, this::handleEntityData) + .register(ClientboundSetEquipmentPacket.class, this::handleSetEquipment) + .register(ClientboundRemoveMobEffectPacket.class, this::handleRemoveMobEffect) + .register(ClientboundUpdateMobEffectPacket.class, this::handleUpdateMobEffect) + .register(ClientboundKeepAlivePacket.class, this::handleKeepAlive) + .register(ClientboundSetPassengersPacket.class, this::handlePassengers) + .registerPost(ClientboundAddEntityPacket.class, this::handleAddEntityPost); + this.readInterceptors = new PacketInterceptor(); + this.readInterceptors + .register(ServerboundAttackPacket.class, this::handleAttack) + .register(ServerboundInteractPacket.class, this::handleInteract) + .register(ServerboundPlayerInputPacket.class, this::handlePlayerInput) + .register(ServerboundPongPacket.class, this::handlePong) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.Pos.class, this::handlePlayerMove) + .register(net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot.class, this::handlePlayerMove) + .register(ServerboundClientTickEndPacket.class, this::handleClientTickEnd); + } + + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + if (!(msg instanceof Packet rawPacket && asClientPacket(rawPacket) instanceof Packet packet)) { + super.write(ctx, msg, promise); + } else { + try { + if (packet instanceof ClientboundBundlePacket bundle) { + ArrayList> list = new ArrayList<>(); + + for (Packet subPacket : bundle.subPackets()) { + Packet result = this.writeInterceptors.accept(subPacket); + if (result != null) { + list.add(result); + Collection> post = this.writeInterceptors.acceptPost(result); + if (!post.isEmpty()) { + list.addAll(post); + } + } + } + + if (!list.isEmpty()) { + Packet var12 = new ClientboundBundlePacket(list); + super.write(ctx, var12, promise); + } + } else { + Packet var13 = this.writeInterceptors.accept(packet); + if (var13 == null) { + return; + } + + Collection> post = this.writeInterceptors.acceptPost(var13); + if (post.isEmpty()) { + super.write(ctx, var13, promise); + } else { + ArrayList> list = new ArrayList<>(post.size() + 1); + list.add(var13); + list.addAll(post); + Packet var14 = new ClientboundBundlePacket(list); + super.write(ctx, var14, promise); + } + } + } catch (Throwable var11) { + var11.printStackTrace(); + } + } + } + + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { + if (!(msg instanceof Packet)) { + super.channelRead(ctx, msg); + } else { + Packet packet = this.readInterceptors.accept((Packet)msg); + if (packet != null) { + super.channelRead(ctx, packet); + this.readInterceptors.acceptPost(packet); + } + } + } + + private ClientboundAddEntityPacket handleAddEntity(ClientboundAddEntityPacket packet) { + int id = packet.getId(); + this.markViewersDirty(id); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private void markViewersDirty(int id) { + ModeledEntity model = this.updaters.getModeledEntity(id); + if (model != null) { + model.getBase().getData().markViewersDirty(); + } + } + + private List> handleAddEntityPost(ClientboundAddEntityPacket packet) { + return this.handleMount(packet.getUUID()); + } + + private List> handleMount(UUID uuid) { + Pair pair = ModelEngineAPI.getMountPairManager().get(uuid); + if (pair == null) { + return null; + } else { + ActiveModel model = (ActiveModel)pair.left(); + List> list = null; + Optional maybeMount = model.getBehaviorRenderer(BoneBehaviorTypes.MOUNT); + if (maybeMount.isPresent() && maybeMount.get() instanceof MountRenderer renderer) { + MountController controller = (MountController)pair.right(); + if (controller.getMount() instanceof BoneBehavior behavior) { + MountRenderer.Mount mount = renderer.getRendered().get(behavior.getBone().getBoneId()); + if (mount == null) { + return null; + } + + CollectionDataTracker ids = mount.getPassengers(); + list = new ArrayList<>(); + list.add(new ClientboundSetPassengersPacket(EntityContainer.of(mount.getMountId(), ids))); + } + } + + return list; + } + } + + private ClientboundRemoveEntitiesPacket handleRemoveEntities(ClientboundRemoveEntitiesPacket packet) { + IntList ids = packet.entityIds(); + + for (int i = 0; i < ids.size(); i++) { + this.markViewersDirty(ids.getInt(i)); + } + + int[] set = packet.entityIds().intStream().filter(id -> ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE).toArray(); + return set.length == packet.entityIds().size() ? packet : new ClientboundRemoveEntitiesPacket(IntArrayList.wrap(set)); + } + + private > T handleEntityId(T packet) { + FriendlyByteBuf buf = NetworkUtils.readClientbound(packet); + + Packet var4; + try { + int id = buf.readVarInt(); + var4 = ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } finally { + buf.release(); + } + + return (T)var4; + } + + private > T handleEntityId(T packet, MethodHandle idGetter) { + int id; + try { + id = (int)idGetter.invoke((Packet)packet); + } catch (Throwable var5) { + throw new IllegalStateException(var5); + } + + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityMotionPacket handleEntityMotion(ClientboundSetEntityMotionPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundTeleportEntityPacket handleTeleportEntity(ClientboundTeleportEntityPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundEntityPositionSyncPacket handlePositionSync(ClientboundEntityPositionSyncPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.id()) != CancelType.HIDE ? packet : null; + } + + private ClientboundAnimatePacket handleAnimate(ClientboundAnimatePacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundSetEntityDataPacket handleEntityData(ClientboundSetEntityDataPacket packet) { + CancelType type = ModelEngineAPI.shouldShow(this.player, packet.id()); + if (type == CancelType.HIDE) { + return null; + } else if (packet.id() != this.player.getEntityId() && type == CancelType.SHOW) { + return packet; + } else { + ModeledEntity modeledEntity = this.updaters.getModeledEntity(packet.id()); + if (modeledEntity == null) { + return packet; + } else { + if (this.entityHandler.isForcedInvisible(modeledEntity.getBase().getUUID())) { + ArrayList> entityData = new ArrayList<>(); + + for (DataValue item : packet.packedItems()) { + if (item.id() == 0) { + byte data = (Byte)item.value(); + data = TMath.setBit(data, 5, true); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, data)); + } else { + entityData.add(item); + } + } + + packet = new ClientboundSetEntityDataPacket(packet.id(), entityData); + } + + return packet; + } + } + } + + private ClientboundSetEquipmentPacket handleSetEquipment(ClientboundSetEquipmentPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntity()) == CancelType.SHOW ? packet : null; + } + + private ClientboundRemoveMobEffectPacket handleRemoveMobEffect(ClientboundRemoveMobEffectPacket packet) { + int id = packet.entityId(); + return ModelEngineAPI.shouldShow(this.player, id) != CancelType.HIDE ? packet : null; + } + + private ClientboundUpdateMobEffectPacket handleUpdateMobEffect(ClientboundUpdateMobEffectPacket packet) { + return ModelEngineAPI.shouldShow(this.player, packet.getEntityId()) != CancelType.HIDE ? packet : null; + } + + private ClientboundKeepAlivePacket handleKeepAlive(ClientboundKeepAlivePacket packet) { + if (this.desyncMonitor.clientTickShifted() || this.desyncMonitor.shouldRetest()) { + this.desyncMonitor.startTest(); + } + + return packet; + } + + private ClientboundSetPassengersPacket handlePassengers(ClientboundSetPassengersPacket packet) { + PivotOverrideRegistry registry = ModelEngineAPI.getPivotOverrideRegistry(); + Optional maybeOverride = registry.get(packet.getVehicle()); + if (maybeOverride.isEmpty()) { + return packet; + } else { + PivotOverride override = maybeOverride.get(); + Collection extra = override.getPassengers().get(); + if (extra.isEmpty()) { + return packet; + } else { + int[] existing = packet.getPassengers(); + IntLinkedOpenHashSet merged = new IntLinkedOpenHashSet(existing.length + extra.size()); + + for (int id : existing) { + merged.add(id); + } + + boolean changed = false; + + for (int id : extra) { + if (merged.add(id)) { + changed = true; + } + } + + return !changed ? packet : new ClientboundSetPassengersPacket(EntityContainer.of(packet.getVehicle(), new IntArrayList(merged))); + } + } + } + + private Packet handleAttack(ServerboundAttackPacket packet) { + int entityId = packet.entityId(); + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundAttackPacketWrapper(hitbox.getTarget(), packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundAttackPacketWrapper(id, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundAttackPacketWrapper(relayed, packet) : packet); + } + } + + private Packet handleInteract(ServerboundInteractPacket packet) { + int entityId = packet.entityId(); + if (entityId == DynamicHitbox.getHitboxId()) { + DynamicHitbox hitbox = ModelEngineAPI.getInteractionTracker().getDynamicHitbox(this.player.getUniqueId()); + if (hitbox != null) { + return new ServerboundInteractPacketWrapper(hitbox.getTarget(), packet); + } + } + + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(entityId); + if (activeModel != null) { + ModeledEntity modeledEntity = activeModel.getModeledEntity(); + if (modeledEntity == null) { + return packet; + } else { + int id = modeledEntity.getBase().getEntityId(); + return new ServerboundInteractPacketWrapper(id, packet); + } + } else { + Integer relayed = ModelEngineAPI.getInteractionTracker().getEntityRelay(entityId); + return (Packet)(relayed != null ? new ServerboundInteractPacketWrapper(relayed, packet) : packet); + } + } + + private ServerboundPlayerInputPacket handlePlayerInput(ServerboundPlayerInputPacket inputPacket) { + MountController controller = ModelEngineAPI.getMountPairManager().getController(this.player.getUniqueId()); + if (controller != null) { + MountController.MountInput input = controller.getInput(); + if (input == null) { + controller.setInput( + new MountController.MountInput( + inputPacket.input().forward(), + inputPacket.input().backward(), + inputPacket.input().left(), + inputPacket.input().right(), + inputPacket.input().jump(), + inputPacket.input().shift(), + inputPacket.input().sprint() + ) + ); + } else { + input.setForward(inputPacket.input().forward()); + input.setBackward(inputPacket.input().backward()); + input.setLeft(inputPacket.input().left()); + input.setRight(inputPacket.input().right()); + input.setJump(inputPacket.input().jump()); + input.setSneak(inputPacket.input().shift()); + input.setSprint(inputPacket.input().sprint()); + } + } + + return inputPacket; + } + + private ServerboundPongPacket handlePong(ServerboundPongPacket packet) { + this.desyncMonitor.recordPongTime(System.currentTimeMillis()); + return null; + } + + private ServerboundMovePlayerPacket handlePlayerMove(ServerboundMovePlayerPacket packet) { + if (!ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + private ServerboundClientTickEndPacket handleClientTickEnd(ServerboundClientTickEndPacket packet) { + if (ConfigProperty.SYNC_CLIENT_TICK_END.getBoolean()) { + this.desyncMonitor.recordClientSyncTime(System.currentTimeMillis()); + } + + return packet; + } + + @SuppressWarnings("unchecked") + private static Packet asClientPacket(Object packet) { + return (Packet)packet; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/NetworkHandlerImpl.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/NetworkHandlerImpl.java new file mode 100644 index 0000000..df7f969 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/NetworkHandlerImpl.java @@ -0,0 +1,139 @@ +package com.ticxo.modelengine.v26_3.network; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.nms.network.ClientDesyncMonitor; +import com.ticxo.modelengine.api.nms.network.NetworkHandler; +import com.ticxo.modelengine.api.nms.network.PipelineWrapper; +import com.ticxo.modelengine.api.nms.network.ProtectedPacketUnpacker; +import com.ticxo.modelengine.v26_3.network.utils.Bundler; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import io.netty.channel.Channel; +import io.netty.channel.ChannelPipeline; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Map.Entry; +import net.minecraft.SharedConstants; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +public class NetworkHandlerImpl implements NetworkHandler { + public static NetworkHandlerImpl instance; + private final Map pipelines = Maps.newConcurrentMap(); + private final Map bundles = Maps.newConcurrentMap(); + private volatile boolean isBatching; + + public NetworkHandlerImpl() { + if (instance != null) { + throw new IllegalStateException("Network handler already initialized"); + } else { + instance = this; + } + } + + @Override + public int getProtocolVersion() { + return SharedConstants.getProtocolVersion(); + } + + @Override + public Optional getPipeline(UUID uuid) { + return Optional.ofNullable(this.pipelines.get(uuid)); + } + + @Override + public void removePipeline(UUID uuid) { + this.pipelines.remove(uuid); + } + + @Override + public void injectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = listener.connection; + ChannelPipeline pipeline = connection.channel.pipeline(); + PipelineWrapper wrapper = new PipelineWrapper(player, connection.channel); + ModelEngineChannelHandler handler = new ModelEngineChannelHandler(player, wrapper); + this.pipelines.put(player.getUniqueId(), wrapper); + this.bundles.put(player.getUniqueId(), new Bundler()); + + for (String name : pipeline.toMap().keySet()) { + if (pipeline.get(name) instanceof Connection) { + pipeline.addBefore(name, "protected_packet_unpacker", new ProtectedPacketUnpacker()); + pipeline.addBefore(name, "model_engine_packet_handler", handler); + break; + } + } + } + + @Override + public void ejectChannel(Player player) { + ServerGamePacketListenerImpl listener = ((CraftPlayer)player).getHandle().connection; + Connection connection = listener.connection; + Channel channel = connection.channel; + channel.eventLoop().submit(() -> { + channel.pipeline().remove("protected_packet_unpacker"); + channel.pipeline().remove("model_engine_packet_handler"); + return null; + }); + this.removePipeline(player.getUniqueId()); + this.bundles.remove(player.getUniqueId()); + } + + @Override + public void ping(UUID uuid) { + this.getPipeline(uuid).ifPresent(wrapper -> { + ClientDesyncMonitor monitor = wrapper.getDesyncMonitor(); + if (monitor.shouldPing()) { + monitor.markPingSent(); + int id = monitor.getPingCounter().getAndIncrement(); + NetworkUtils.sendNow(uuid, new ClientboundPingPacket(id)); + } + }); + } + + @Override + public void startBatch() { + this.isBatching = true; + } + + @Override + public void endBatch() { + this.isBatching = false; + + for (Entry entry : this.bundles.entrySet()) { + PipelineWrapper pipeline = this.pipelines.get(entry.getKey()); + if (pipeline != null) { + Bundler bundler = entry.getValue(); + synchronized (bundler) { + bundler.bundle(pipeline::writeAndFlush); + bundler.clear(); + } + } + } + } + + public void appendPacket(UUID uuid, Packet packet) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(packet); + } + } + + public void appendPackets(UUID uuid, Collection> collection) { + Bundler bundler = this.bundles.get(uuid); + if (bundler != null) { + bundler.appendPacket(collection); + } + } + + @Override + public boolean isBatching() { + return this.isBatching; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/PatchedServerGamePacketListener.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/PatchedServerGamePacketListener.java new file mode 100644 index 0000000..038cc81 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/PatchedServerGamePacketListener.java @@ -0,0 +1,392 @@ +package com.ticxo.modelengine.v26_3.network.patch; + +import com.mojang.datafixers.util.Pair; +import com.mojang.logging.LogUtils; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.events.BaseEntityInteractEvent; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.bone.ModelBone; +import com.ticxo.modelengine.api.nms.entity.EntityHandler; +import com.ticxo.modelengine.api.nms.entity.HitboxEntity; +import com.ticxo.modelengine.api.utils.ReflectionUtils; +import com.ticxo.modelengine.v26_3.NMSMethods; +import io.papermc.paper.configuration.GlobalConfiguration; +import io.papermc.paper.util.MCUtil; +import java.util.Arrays; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import net.minecraft.advancements.triggers.CriteriaTriggers; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundUseItemPacket; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResult.Success; +import net.minecraft.world.InteractionResult.SwingSource; +import net.minecraft.world.entity.Bucketable; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.Leashable; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.animal.allay.Allay; +import net.minecraft.world.entity.animal.equine.AbstractHorse; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.projectile.arrow.AbstractArrow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.component.SwingAnimation; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.HitResult.Type; +import org.bukkit.craftbukkit.CraftEquipmentSlot; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.util.CraftVector; +import org.bukkit.event.Event.Result; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerKickEvent.Cause; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; +import org.slf4j.Logger; + +public class PatchedServerGamePacketListener { + private static final Logger LOGGER = LogUtils.getLogger(); + + public static void handleAttack(ServerboundAttackPacketWrapper attackPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(attackPacket, connection, connection.getPlayer().level()); + ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + if (connection.hasClientLoaded()) { + CraftPlayer craftPlayer = player.getBukkitEntity(); + ServerLevel level = player.level(); + CraftServer craftServer = level.getServer().server; + Entity target = level.getEntityOrPart(attackPacket.getRelayedId()); + if (target != player || player.isSpectator()) { + player.resetLastActionTime(); + callBaseEntityEvents( + attackPacket, + (base, model, hitBone) -> craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.ATTACK, + EquipmentSlot.HAND, + player.isShiftKeyDown(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null, + hitBone + ) + ) + ); + if (target != null && level.getWorldBorder().isWithinBounds(target.blockPosition())) { + AABB targetBounds = target.getBoundingBox(); + ItemStack mainHandItem = player.getMainHandItem(); + if (player.isWithinAttackRange(mainHandItem, targetBounds, GlobalConfiguration.get().misc.clientInteractionLeniencyDistance.or(3.0)) + && !mainHandItem.has(DataComponents.PIERCING_WEAPON)) { + if (target instanceof ItemEntity + || target instanceof ExperienceOrb + || target == player + || target instanceof AbstractArrow abstractArrow && !abstractArrow.isAttackable()) { + connection.disconnect(Component.translatable("multiplayer.disconnect.invalid_entity_attacked"), Cause.INVALID_ENTITY_ATTACKED); + LOGGER.warn("Player {} tried to attack an invalid entity", player.getPlainTextName()); + } else if (mainHandItem.isItemEnabled(level.enabledFeatures()) && !player.cannotAttackWithItem(mainHandItem, 5)) { + player.attack(target); + } + } + } else if (target == null) { + CraftEventFactory.callPlayerUseUnknownEntityEvent(player, attackPacket.getOriginalId(), true, InteractionHand.MAIN_HAND, null); + } + + if (GlobalConfiguration.get().unsupportedSettings.updateEquipmentOnPlayerActions) { + player.detectEquipmentUpdates(); + } + } + } + } + } + } + + public static void handleInteract(ServerboundInteractPacketWrapper interactPacket, ServerGamePacketListener listener) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + PacketUtils.ensureRunningOnSameThread(interactPacket, connection, connection.getPlayer().level()); + ServerPlayer player = connection.getPlayer(); + if (!player.isImmobile()) { + if (connection.hasClientLoaded()) { + CraftPlayer craftPlayer = player.getBukkitEntity(); + ServerLevel level = player.level(); + CraftServer craftServer = level.getServer().server; + Entity target = level.getEntityOrPart(interactPacket.getRelayedId()); + if (interactPacket.isFakeInteraction()) { + EntityHandler entityHandler = ModelEngineAPI.getNMSHandler().getEntityHandler(); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.HAND); + entityHandler.forceUseItem(craftPlayer, EquipmentSlot.OFF_HAND); + } + + if (target != player || player.isSpectator()) { + player.resetLastActionTime(); + player.setShiftKeyDown(interactPacket.isUsingSecondaryAction()); + callBaseEntityEvents( + interactPacket, + (base, model, hitBone) -> { + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + null, + hitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + null, + hitBone + ) + ); + Vec3 pos = interactPacket.getLocation(); + Vector position = new Vector(pos.x, pos.y, pos.z); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT_ON, + EquipmentSlot.HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.HAND), + position, + hitBone + ) + ); + craftServer.getPluginManager() + .callEvent( + new BaseEntityInteractEvent( + craftPlayer, + base, + model, + BaseEntityInteractEvent.Action.INTERACT_ON, + EquipmentSlot.OFF_HAND, + interactPacket.isUsingSecondaryAction(), + craftPlayer.getInventory().getItem(EquipmentSlot.OFF_HAND), + position, + hitBone + ) + ); + } + ); + if (target != null && level.getWorldBorder().isWithinBounds(target.blockPosition())) { + AABB targetBounds = target.getBoundingBox(); + if (player.isWithinEntityInteractionRange(targetBounds, GlobalConfiguration.get().misc.clientInteractionLeniencyDistance.or(3.0))) { + InteractionHand hand = interactPacket.getHand(); + Vec3 location = interactPacket.getLocation(); + ItemStack tool = player.getItemInHand(hand); + if (tool.isItemEnabled(level.enabledFeatures())) { + ItemStack usedItemStack = tool.copy(); + Item itemType = tool.getItem(); + boolean triggerLeashUpdate = usedItemStack.is(Items.LEAD) && target instanceof Leashable; + PlayerInteractAtEntityEvent event = new PlayerInteractAtEntityEvent( + connection.getCraftPlayer(), target.getBukkitEntity(), CraftVector.toBukkit(location), CraftEquipmentSlot.getHand(hand) + ); + connection.cserver.getPluginManager().callEvent(event); + boolean resendData = event.isCancelled() || !player.getItemInHand(hand).is(itemType); + if (itemType == Items.WATER_BUCKET && target instanceof Bucketable && target instanceof LivingEntity && resendData) { + target.resendPossiblyDesyncedEntityData(player); + } + + if (resendData) { + if (MCUtil.clientPredictsInteraction(player, target, tool)) { + player.containerMenu.sendAllDataToRemote(); + } else { + player.containerMenu.forceHeldSlot(hand); + } + } + + if (triggerLeashUpdate && resendData) { + connection.send(new ClientboundSetEntityLinkPacket(target, ((Leashable)target).getLeashHolder())); + } + + if (resendData) { + target.refreshEntityData(player); + if (!(target instanceof Allay) && !(target instanceof AbstractHorse)) { + player.containerMenu.forceHeldSlot(hand); + } else { + connection.send( + new ClientboundSetEquipmentPacket( + target.getId(), + Arrays.stream(net.minecraft.world.entity.EquipmentSlot.values()) + .map(slot -> Pair.of(slot, ((LivingEntity)target).getItemBySlot(slot).copy())) + .collect(Collectors.toList()), + true + ) + ); + player.containerMenu.sendAllDataToRemote(); + } + } + + if (event.isCancelled()) { + return; + } + + if (player.interactOn(target, hand, location) instanceof Success success) { + ItemStack awardedForStack = success.wasItemInteraction() ? usedItemStack : ItemStack.EMPTY; + CriteriaTriggers.PLAYER_INTERACTED_WITH_ENTITY.trigger(player, awardedForStack, target); + if (success.shouldSwing()) { + SwingAnimation swingAnimation = usedItemStack.getInteractAnimation(); + player.swingAndResetAttackStrength(hand, swingAnimation, success.swingSource() != SwingSource.PREDICTED); + } + } + } + } + } else if (target == null) { + CraftEventFactory.callPlayerUseUnknownEntityEvent( + player, interactPacket.getOriginalId(), false, interactPacket.getHand(), interactPacket.getLocation() + ); + } + + if (GlobalConfiguration.get().unsupportedSettings.updateEquipmentOnPlayerActions) { + player.detectEquipmentUpdates(); + } + } + } + } + } + } + + public static void handleUseItem(ServerboundUseItemPacket packet, ServerGamePacketListener listener, Consumer afterUse) { + if (listener instanceof ServerGamePacketListenerImpl connection) { + ServerPlayer player = connection.getPlayer(); + PacketUtils.ensureRunningOnSameThread(packet, connection, player.level()); + if (!player.isImmobile()) { + boolean shouldLimit = Boolean.TRUE + .equals(ReflectionUtils.call(connection, NMSMethods.SERVER_GAME_PACKET_LISTENER_IMPL_checkLimit, packet.timestamp())); + if (shouldLimit) { + if (connection.hasClientLoaded()) { + connection.ackBlockChangesUpTo(packet.sequence()); + ServerLevel level = player.level(); + InteractionHand hand = packet.hand(); + ItemStack itemStack = player.getItemInHand(hand); + player.resetLastActionTime(); + if (!itemStack.isEmpty() && itemStack.isItemEnabled(level.enabledFeatures())) { + SwingAnimation swingAnimation = itemStack.getInteractAnimation(); + float targetYRot = Mth.wrapDegrees(packet.yRot()); + float targetXRot = Mth.wrapDegrees(packet.xRot()); + if (targetXRot != player.getXRot() || targetYRot != player.getYRot()) { + player.absSnapRotationTo(targetYRot, targetXRot); + } + + Vec3 from = player.getEyePosition(); + Vec3 delta = player.getViewVector(1.0F).scale(player.blockInteractionRange()); + Vec3 to = from.add(delta); + BlockHitResult hitResult = player.level().clip(new ClipContext(from, to, Block.OUTLINE, Fluid.NONE, player)); + boolean cancelled; + if (hitResult.getType() != Type.BLOCK) { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_AIR, itemStack, hand); + cancelled = event.useItemInHand() == Result.DENY; + } else { + if (player.gameMode.firedInteract + && player.gameMode.interactPosition.equals(hitResult.getBlockPos()) + && player.gameMode.interactHand == hand + && ItemStack.isSameItemSameComponents(player.gameMode.interactItemStack, itemStack)) { + cancelled = player.gameMode.interactResult; + } else { + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent( + player, + Action.RIGHT_CLICK_BLOCK, + hitResult.getBlockPos(), + hitResult.getDirection(), + itemStack, + true, + hand, + hitResult.getLocation() + ); + cancelled = event.useItemInHand() == Result.DENY; + } + + player.gameMode.firedInteract = false; + } + + if (cancelled) { + player.resyncUsingItem(player); + if (MCUtil.clientPredictsInteraction(player, Blocks.AIR.defaultBlockState(), itemStack)) { + player.containerMenu.sendAllDataToRemote(); + } else { + player.containerMenu.forceHeldSlotAndArmor(hand); + } + + return; + } + + itemStack = player.getItemInHand(hand); + if (itemStack.isEmpty()) { + return; + } + + InteractionResult result = player.gameMode.useItem(player, level, itemStack, hand); + afterUse.accept(result); + if (result instanceof Success success && success.shouldSwing()) { + player.swingAndResetAttackStrength(hand, swingAnimation, success.swingSource() != SwingSource.PREDICTED); + } + } + } + } + } + } + } + + private static void callBaseEntityEvents(RelayedPacketWrapper relayedPacket, PatchedServerGamePacketListener.BaseEntityEventCallback callback) { + ModelBone hitBone = null; + ActiveModel activeModel = ModelEngineAPI.getInteractionTracker().getModelRelay(relayedPacket.getOriginalId()); + if (activeModel == null) { + HitboxEntity hitbox = ModelEngineAPI.getInteractionTracker().getHitbox(relayedPacket.getRelayedId()); + if (hitbox != null) { + hitBone = hitbox.getBone(); + activeModel = hitBone.getActiveModel(); + } + } + + if (activeModel != null) { + BaseEntity base = activeModel.getModeledEntity().getBase(); + callback.call(base, activeModel, hitBone); + } + } + + @FunctionalInterface + private interface BaseEntityEventCallback { + void call(BaseEntity var1, ActiveModel var2, ModelBone var3); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/RelayedPacketWrapper.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/RelayedPacketWrapper.java new file mode 100644 index 0000000..f4a1d92 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/RelayedPacketWrapper.java @@ -0,0 +1,24 @@ +package com.ticxo.modelengine.v26_3.network.patch; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ServerGamePacketListener; + +public abstract class RelayedPacketWrapper> implements Packet { + private final int relayedId; + private final T original; + + protected RelayedPacketWrapper(int relayedId, T original) { + this.relayedId = relayedId; + this.original = original; + } + + abstract int getOriginalId(); + + public int getRelayedId() { + return this.relayedId; + } + + public T getOriginal() { + return this.original; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/ServerboundAttackPacketWrapper.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/ServerboundAttackPacketWrapper.java new file mode 100644 index 0000000..b7c2ae9 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/ServerboundAttackPacketWrapper.java @@ -0,0 +1,28 @@ +package com.ticxo.modelengine.v26_3.network.patch; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundAttackPacket; +import org.jetbrains.annotations.NotNull; + +public class ServerboundAttackPacketWrapper extends RelayedPacketWrapper { + public ServerboundAttackPacketWrapper(int relayedId, ServerboundAttackPacket original) { + super(relayedId, original); + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_ATTACK; + } + + public void handle(ServerGamePacketListener listener) { + PatchedServerGamePacketListener.handleAttack(this, listener); + } + + @Override + public int getOriginalId() { + return this.getOriginal().entityId(); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/ServerboundInteractPacketWrapper.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/ServerboundInteractPacketWrapper.java new file mode 100644 index 0000000..449302a --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/patch/ServerboundInteractPacketWrapper.java @@ -0,0 +1,49 @@ +package com.ticxo.modelengine.v26_3.network.patch; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.interaction.InteractionTracker; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketType; +import net.minecraft.network.protocol.game.GamePacketTypes; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; + +public class ServerboundInteractPacketWrapper extends RelayedPacketWrapper { + public ServerboundInteractPacketWrapper(int relayedId, ServerboundInteractPacket original) { + super(relayedId, original); + } + + @NotNull + public PacketType> type() { + return GamePacketTypes.SERVERBOUND_INTERACT; + } + + public void handle(ServerGamePacketListener listener) { + PatchedServerGamePacketListener.handleInteract(this, listener); + } + + @Override + public int getOriginalId() { + return this.getOriginal().entityId(); + } + + public InteractionHand getHand() { + return this.getOriginal().hand(); + } + + public boolean isUsingSecondaryAction() { + return this.getOriginal().usingSecondaryAction(); + } + + public Vec3 getLocation() { + return this.getOriginal().location(); + } + + public boolean isFakeInteraction() { + InteractionTracker tracker = ModelEngineAPI.getInteractionTracker(); + return tracker.getModelRelay(this.getOriginalId()) != null || tracker.getEntityRelay(this.getOriginalId()) != null; + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/BulkEntityDataEncoder.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/BulkEntityDataEncoder.java new file mode 100644 index 0000000..0e57e71 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/BulkEntityDataEncoder.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v26_3.network.utils; + +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class BulkEntityDataEncoder { + private static final byte PACKET_TYPE_BULK_DATA = 0; + public static final int FIELD_TRANSLATION = 0; + public static final int FIELD_LEFT_ROTATION = 1; + public static final int FIELD_SCALE = 2; + public static final int FIELD_RIGHT_ROTATION = 3; + public static final int FIELD_TRANSFORM_DURATION = 4; + public static final int FIELD_GLOW_DATA = 5; + public static final int FIELD_BRIGHTNESS = 6; + public static final int FIELD_RENDER_DATA = 7; + private final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer(256)); + private int entryCount; + private final int entryCountIndex; + + public BulkEntityDataEncoder() { + this.buf.writeByte(0); + this.entryCountIndex = this.buf.writerIndex(); + this.buf.writeVarInt(0); + this.entryCount = 0; + } + + public BulkEntityDataEncoder.EntryWriter startEntry(int entityId) { + this.entryCount++; + this.buf.writeVarInt(entityId); + return new BulkEntityDataEncoder.EntryWriter(this.buf); + } + + public byte[] build() { + int endIndex = this.buf.writerIndex(); + this.buf.writerIndex(this.entryCountIndex); + this.buf.writeVarInt(this.entryCount); + this.buf.writerIndex(endIndex); + byte[] data = new byte[this.buf.readableBytes()]; + this.buf.getBytes(this.buf.readerIndex(), data); + this.buf.release(); + return data; + } + + public int getEntryCount() { + return this.entryCount; + } + + public static short floatToHalf(float f) { + int bits = Float.floatToRawIntBits(f); + int sign = bits >>> 16 & 32768; + int exp = (bits >>> 23 & 0xFF) - 127; + int mantissa = bits & 8388607; + if (exp >= 16) { + return (short)(sign | 31744); + } else if (exp >= -14) { + return (short)(sign | exp + 15 << 10 | mantissa >>> 13); + } else if (exp >= -24) { + int shift = -14 - exp; + return (short)(sign | (8388608 | mantissa) >>> 13 + shift); + } else { + return (short)sign; + } + } + + private static void writeHalf(FriendlyByteBuf buf, float f) { + buf.writeShort(floatToHalf(f)); + } + + public static class EntryWriter { + private final FriendlyByteBuf buf; + private final int bitmaskIndex; + private byte bitmask; + + EntryWriter(FriendlyByteBuf buf) { + this.buf = buf; + this.bitmaskIndex = buf.writerIndex(); + buf.writeByte(0); + this.bitmask = 0; + } + + public BulkEntityDataEncoder.EntryWriter translation(Vector3f pos) { + this.bitmask = (byte)(this.bitmask | 1); + BulkEntityDataEncoder.writeHalf(this.buf, pos.x); + BulkEntityDataEncoder.writeHalf(this.buf, pos.y); + BulkEntityDataEncoder.writeHalf(this.buf, pos.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter leftRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 2); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter scale(Vector3f scale) { + this.bitmask = (byte)(this.bitmask | 4); + BulkEntityDataEncoder.writeHalf(this.buf, scale.x); + BulkEntityDataEncoder.writeHalf(this.buf, scale.y); + BulkEntityDataEncoder.writeHalf(this.buf, scale.z); + return this; + } + + public BulkEntityDataEncoder.EntryWriter rightRotation(Quaternionf rot) { + this.bitmask = (byte)(this.bitmask | 8); + BulkEntityDataEncoder.writeHalf(this.buf, rot.x); + BulkEntityDataEncoder.writeHalf(this.buf, rot.y); + BulkEntityDataEncoder.writeHalf(this.buf, rot.z); + BulkEntityDataEncoder.writeHalf(this.buf, rot.w); + return this; + } + + public BulkEntityDataEncoder.EntryWriter transformDuration(int duration) { + this.bitmask = (byte)(this.bitmask | 16); + this.buf.writeVarInt(duration); + return this; + } + + public BulkEntityDataEncoder.EntryWriter glowData(byte sharedData, int glowColor) { + this.bitmask = (byte)(this.bitmask | 32); + this.buf.writeByte(sharedData); + this.buf.writeInt(glowColor); + return this; + } + + public BulkEntityDataEncoder.EntryWriter brightness(int brightness) { + this.bitmask = (byte)(this.bitmask | 64); + this.buf.writeInt(brightness); + return this; + } + + public BulkEntityDataEncoder.EntryWriter renderData(byte billboard, float viewRange, byte displayType) { + this.bitmask = (byte)(this.bitmask | 128); + this.buf.writeByte(billboard); + this.buf.writeFloat(viewRange); + this.buf.writeByte(displayType); + return this; + } + + public void finish() { + this.buf.setByte(this.bitmaskIndex, this.bitmask); + } + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/Bundler.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/Bundler.java new file mode 100644 index 0000000..8b194df --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/Bundler.java @@ -0,0 +1,65 @@ +package com.ticxo.modelengine.v26_3.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.config.ConfigProperty; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; + +public class Bundler { + private static int BUNDLE_SIZE; + private final List>> bundles = new ArrayList<>(); + + public synchronized void appendPacket(Packet packet) { + if (this.bundles.isEmpty()) { + this.bundles.add(new ArrayList<>()); + } + + List> bundleList = this.bundles.getLast(); + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + + public synchronized void appendPacket(Collection> packets) { + if (!packets.isEmpty()) { + List> bundleList = this.bundles.isEmpty() ? null : this.bundles.getLast(); + if (bundleList == null || bundleList.size() + packets.size() > BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + for (Packet packet : packets) { + if (bundleList.size() == BUNDLE_SIZE) { + bundleList = new ArrayList<>(); + this.bundles.add(bundleList); + } + + bundleList.add(packet); + } + } + } + + public void clear() { + this.bundles.clear(); + } + + public void bundle(Consumer send) { + for (List> list : this.bundles) { + ProtectedPacket wrapped = new ProtectedPacket(new ClientboundBundlePacket(list)); + send.accept(wrapped); + } + } + + static { + ModelEngineAPI.getAPI().getConfigManager().registerReferenceUpdate(() -> BUNDLE_SIZE = Math.min(ConfigProperty.BUNDLE_SIZE.getInt(), 4096)); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/NetworkUtils.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/NetworkUtils.java new file mode 100644 index 0000000..f71a6a8 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/NetworkUtils.java @@ -0,0 +1,356 @@ +package com.ticxo.modelengine.v26_3.network.utils; + +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.nms.network.ProtectedPacket; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v26_3.entity.EntityContainer; +import com.ticxo.modelengine.v26_3.network.NetworkHandlerImpl; +import io.netty.buffer.Unpooled; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Predicate; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.ProtocolInfo; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.GameProtocols.Context; +import net.minecraft.network.protocol.game.VecDelta.Linear; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; + +public class NetworkUtils { + public static final ProtocolInfo CLIENTBOUND_CODEC = GameProtocols.CLIENTBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess())); + public static final ProtocolInfo SERVERBOUND_CODEC = GameProtocols.SERVERBOUND_TEMPLATE + .bind(RegistryFriendlyByteBuf.decorator(MinecraftServer.getServer().registryAccess()), new Context() { + public boolean hasInfiniteMaterials() { + return false; + } + + public boolean canUseCommandBlocks() { + return false; + } + }); + private static final Map, Constructor> PACKET_CONSTRUCTOR = new HashMap<>(); + + public static RegistryFriendlyByteBuf createByteBuf() { + return new RegistryFriendlyByteBuf(Unpooled.buffer(), MinecraftServer.getServer().registryAccess()); + } + + public static RegistryFriendlyByteBuf createByteBuf(Consumer consumer) { + RegistryFriendlyByteBuf buf = createByteBuf(); + consumer.accept(buf); + return buf; + } + + public static > T create(Class clazz, RegistryFriendlyByteBuf buf) { + Constructor constructor = PACKET_CONSTRUCTOR.computeIfAbsent(clazz, aClass -> { + try { + Constructor c = aClass.getDeclaredConstructor(RegistryFriendlyByteBuf.class); + c.setAccessible(true); + return c; + } catch (NoSuchMethodException var4x) { + try { + Constructor cx = aClass.getDeclaredConstructor(FriendlyByteBuf.class); + cx.setAccessible(true); + return cx; + } catch (NoSuchMethodException var3) { + throw new RuntimeException(var3); + } + } + }); + + try { + return (T)constructor.newInstance(buf); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException var4) { + throw new RuntimeException(var4); + } + } + + public static FriendlyByteBuf readServerbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + SERVERBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static FriendlyByteBuf readClientbound(Packet packet) { + RegistryFriendlyByteBuf buf = createByteBuf(); + CLIENTBOUND_CODEC.codec().encode(buf, packet); + buf.readVarInt(); + return buf; + } + + public static Packets.PacketSupplier createPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 + ? new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.5, pos.z, 0.0F, 0.0F, EntityTypes.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0) + : new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y - 0.375, pos.z, 0.0F, 0.0F, EntityTypes.AREA_EFFECT_CLOUD, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createCameraPivotSpawn(int id, UUID uuid, Vector3f pos, float height) { + ClientboundAddEntityPacket packet = new ClientboundAddEntityPacket( + id, uuid, pos.x, pos.y - height, pos.z, 0.0F, 0.0F, EntityTypes.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createCameraPivotTeleport(int id, Vector3f pos, float height) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - height, pos.z); + ClientboundEntityPositionSyncPacket packet = ClientboundEntityPositionSyncPacket.of(container); + return playerUUID -> packet; + } + + public static Packets.PacketSupplier createDisplayPivotSpawn(int id, UUID uuid, Vector3f pos) { + return playerUUID -> new ClientboundAddEntityPacket(id, uuid, pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + public static Packets.PacketSupplier createPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y - 0.375, pos.z); + ClientboundEntityPositionSyncPacket tpHigher = ClientboundEntityPositionSyncPacket.of(container); + container = EntityContainer.of(id); + container.setId(id); + container.setPosRaw(pos.x, pos.y - 0.5, pos.z); + ClientboundEntityPositionSyncPacket tpLower = ClientboundEntityPositionSyncPacket.of(container); + return playerUUID -> ModelEngineAPI.getPlayerProtocolVersion(playerUUID) >= 764 ? tpLower : tpHigher; + } + + public static Object createPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos) { + if (codec == null) { + return createPivotTeleport(id, pos); + } else { + return switch (codec.update(pos.x, pos.y, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, new Linear(codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ()), false); + case ABSOLUTE -> createPivotTeleport(id, pos); + }; + } + } + + public static Object createCameraPivotMove(int id, @Nullable PositionCodec codec, Vector3f pos, float height) { + if (codec == null) { + return createCameraPivotTeleport(id, pos, height); + } else { + return switch (codec.update(pos.x, pos.y - height, pos.z)) { + case UNCHANGED -> null; + case MOVE -> new Pos(id, new Linear(codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ()), false); + case ABSOLUTE -> createCameraPivotTeleport(id, pos, height); + }; + } + } + + public static Packets.PacketSupplier createDisplayPivotTeleport(int id, Vector3f pos) { + EntityContainer container = EntityContainer.of(id); + container.setPosRaw(pos.x, pos.y, pos.z); + return playerUUID -> ClientboundEntityPositionSyncPacket.of(container); + } + + public static Packets.PacketSupplier lodWrapper( + ModeledEntity modeledEntity, BiFunction> packetFunction + ) { + return uuid -> { + AnimationLODHandler.LODTracker tracker = modeledEntity.getAnimationLodHandler().tick(uuid); + return tracker.isCanSkip() ? null : packetFunction.apply(uuid, tracker); + }; + } + + public static void send(UUID target, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPacket(target, packet); + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + + public static void send(Set targets, @Nullable Packet packet) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + handler.appendPacket(player, packet); + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + + public static void send(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + handler.appendPacket(player, packet); + } + } + } else { + ProtectedPacket wrapped = new ProtectedPacket(packet); + + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + } + } + } + } + + public static void sendRaw(UUID target, @Nullable Packet packet) { + if (packet != null) { + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet) { + if (packet != null) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + + public static void sendRaw(Set targets, @Nullable Packet packet, Predicate predicate) { + if (packet != null) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + } + } + } + } + + public static void sendNow(UUID target, @Nullable Packet packet) { + if (packet != null) { + ProtectedPacket wrapped = new ProtectedPacket(packet); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlushNow(wrapped)); + } + } + + private static Packet bundle(Collection> packets) { + return (Packet)(packets.size() == 1 ? packets.iterator().next() : new ClientboundBundlePacket(packets)); + } + + public static void sendBundled(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + handler.appendPackets(target, packets); + } else { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + handler.getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(wrapped)); + } + }); + } + } + + public static void sendBundled(Set targets, Packets collection) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } else { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + + public static void sendBundled(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + NetworkHandlerImpl handler = NetworkHandlerImpl.instance; + if (handler.isBatching()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + collection.compile(player, packets -> handler.appendPackets(player, packets)); + } + } + } else { + for (UUID playerx : targets) { + Player p = Bukkit.getPlayer(playerx); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(playerx).ifPresent(pipeline -> collection.compile(playerx, packets -> { + ProtectedPacket wrapped = new ProtectedPacket(bundle(packets)); + pipeline.writeAndFlush(wrapped); + })); + } + } + } + } + } + + public static void sendBundledRaw(UUID target, Packets collection) { + if (!collection.isEmpty()) { + collection.compile(target, packets -> { + Packet packet = bundle(packets); + ModelEngineAPI.getNetworkHandler().getPipeline(target).ifPresent(pipeline -> pipeline.writeAndFlush(packet)); + }); + } + } + + public static void sendBundledRaw(Set targets, Packets collection) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + + public static void sendBundledRaw(Set targets, Packets collection, Predicate predicate) { + if (!collection.isEmpty()) { + for (UUID player : targets) { + Player p = Bukkit.getPlayer(player); + if (p != null && predicate.test(p)) { + ModelEngineAPI.getNetworkHandler().getPipeline(player).ifPresent(pipeline -> collection.compile(player, packets -> { + Packet packet = bundle(packets); + pipeline.writeAndFlush(packet); + })); + } + } + } + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/PacketInterceptor.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/PacketInterceptor.java new file mode 100644 index 0000000..7dbbec6 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/PacketInterceptor.java @@ -0,0 +1,89 @@ +package com.ticxo.modelengine.v26_3.network.utils; + +import com.google.common.collect.Maps; +import com.ticxo.modelengine.api.utils.logger.TLogger; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; + +public class PacketInterceptor

    { + private final Map>, PacketInterceptor

    .Modifier>> registry = Maps.newConcurrentMap(); + private final Map>, PacketInterceptor

    .Listener>> postRegistry = Maps.newConcurrentMap(); + + public > PacketInterceptor

    register(Class clazz, Function> function) { + this.registry.put(clazz, new Modifier<>(clazz, function)); + return this; + } + + public > PacketInterceptor

    registerPost(Class clazz, Function>> consumer) { + this.postRegistry.put(clazz, new Listener<>(clazz, consumer)); + return this; + } + + public Packet accept(Packet original) { + if (original == null) { + return null; + } else { + PacketInterceptor

    .Modifier modifier = this.registry.get(original.getClass()); + return modifier == null ? original : modifier.modify(original); + } + } + + public Collection> acceptPost(Packet original) { + if (original == null) { + return List.of(); + } else { + PacketInterceptor

    .Listener listener = this.postRegistry.get(original.getClass()); + return (Collection>)(listener != null ? listener.listen(original) : List.of()); + } + } + + class Listener> { + private final Class clazz; + private final Function>> function; + + public Collection> listen(Packet original) { + try { + Collection> collection = this.function.apply(this.clazz.cast(original)); + return (Collection>)(collection == null ? List.of() : collection); + } catch (Throwable var3) { + TLogger.error("An error had occurred while intercepting the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return List.of(); + } + } + + public Listener(final Class clazz, final Function>> function) { + Objects.requireNonNull(PacketInterceptor.this); + super(); + this.clazz = clazz; + this.function = function; + } + } + + class Modifier> { + private final Class clazz; + private final Function> function; + + public Packet modify(Packet original) { + try { + return this.function.apply(this.clazz.cast(original)); + } catch (Throwable var3) { + TLogger.error("An error had occurred while modifying the packet " + this.clazz.getSimpleName()); + var3.printStackTrace(); + return original; + } + } + + public Modifier(final Class clazz, final Function> function) { + Objects.requireNonNull(PacketInterceptor.this); + super(); + this.clazz = clazz; + this.function = function; + } + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/Packets.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/Packets.java new file mode 100644 index 0000000..36bfdb3 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/network/utils/Packets.java @@ -0,0 +1,64 @@ +package com.ticxo.modelengine.v26_3.network.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.function.Consumer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.jetbrains.annotations.NotNull; + +public class Packets extends ArrayList { + public Packets(int initialCapacity, float loadFactor) { + super(initialCapacity); + } + + public Packets(int initialCapacity) { + super(initialCapacity); + } + + public Packets() { + } + + public Packets(@NotNull Collection c) { + super((Collection)c); + } + + @Override + public boolean add(Object obj) { + return obj == null ? false : super.add(obj); + } + + public boolean add(Packet packet) { + return packet == null ? false : super.add(packet); + } + + private Collection> compile(UUID player) { + Collection> list = new ArrayList<>(); + + for (Object obj : this) { + if (obj instanceof Packet) { + list.add((Packet)obj); + } else if (obj instanceof Packets.PacketSupplier supplier) { + Packet packet = supplier.supply(player); + if (packet != null) { + list.add(packet); + } + } + } + + return list; + } + + public void compile(UUID player, Consumer>> ifNotEmpty) { + Collection> set = this.compile(player); + if (!set.isEmpty()) { + ifNotEmpty.accept(set); + } + } + + @FunctionalInterface + public interface PacketSupplier { + Packet supply(UUID var1); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/HeldItemParser.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/HeldItemParser.java new file mode 100644 index 0000000..6fc89c2 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/HeldItemParser.java @@ -0,0 +1,186 @@ +package com.ticxo.modelengine.v26_3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.HeldItemRenderer; +import com.ticxo.modelengine.api.utils.data.PositionCodec; +import com.ticxo.modelengine.v26_3.entity.EntityContainer; +import com.ticxo.modelengine.v26_3.entity.EntityUtils; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundEntityPositionSyncPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Pos; +import net.minecraft.network.protocol.game.VecDelta.Linear; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Quaternionf; + +public class HeldItemParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(HeldItemRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(HeldItemRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + set.add((Packet)this.pivotSpawn(location, renderer)); + set.add((Packet)this.pivotData(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + set.add((Packet)this.mount(renderer)); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(renderer)); + + for (HeldItemRenderer.Item item : renderer.getRendered().values()) { + set.add((Packet)this.itemData(item, false)); + } + + Location location = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + + for (HeldItemRenderer.Item item : renderer.getSpawnQueue().values()) { + set.add((Packet)this.itemSpawn(location, item)); + set.add((Packet)this.itemData(item, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapToInt(HeldItemRenderer.Item::getId)) + )) + ); + } + + if (renderer.getPassengers().isDirty()) { + set.add((Packet)this.mount(renderer)); + renderer.getPassengers().clearDirty(); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, HeldItemRenderer renderer) { + if (!targets.isEmpty()) { + Map items = renderer.getRendered(); + IntArrayList entityIds = IntArrayList.toList(items.values().stream().mapToInt(HeldItemRenderer.Item::getId)); + entityIds.add(renderer.getId()); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private ClientboundAddEntityPacket pivotSpawn(Location location, HeldItemRenderer renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityTypes.ARMOR_STAND, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(HeldItemRenderer renderer) { + return new ClientboundSetEntityDataPacket(renderer.getId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundAddEntityPacket itemSpawn(Location location, HeldItemRenderer.Item renderer) { + return new ClientboundAddEntityPacket( + renderer.getId(), renderer.getUuid(), location.getX(), location.getY(), location.getZ(), 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket itemData(HeldItemRenderer.Item renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(11); + if (spawn) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, this.viewRange)); + } else if (renderer.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + renderer.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), spawn); + renderer.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), spawn); + renderer.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + renderer.getRotation() + .ifDirty( + quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf.rotateY((float) Math.PI, new Quaternionf()))), + spawn + ); + renderer.getModel() + .ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + renderer.getDisplay() + .ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getId(), entityData); + } + } + + private Object teleport(HeldItemRenderer renderer) { + Location loc = renderer.getActiveModel().getModeledEntity().getBase().getLocation(); + PositionCodec codec = renderer.getPositionCodec(); + if (codec != null) { + switch (codec.update(loc.getX(), loc.getY(), loc.getZ())) { + case UNCHANGED: + return null; + case MOVE: + return new Pos(renderer.getId(), new Linear(codec.getDeltaX(), codec.getDeltaY(), codec.getDeltaZ()), false); + case ABSOLUTE: + } + } + + EntityContainer container = EntityContainer.of(renderer.getId()); + container.setPosRaw(loc.getX(), loc.getY(), loc.getZ()); + return ClientboundEntityPositionSyncPacket.of(container); + } + + private ClientboundSetPassengersPacket mount(HeldItemRenderer renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getId(), renderer.getPassengers())); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/LeashParser.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/LeashParser.java new file mode 100644 index 0000000..16a7532 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/LeashParser.java @@ -0,0 +1,158 @@ +package com.ticxo.modelengine.v26_3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.LeashRenderer; +import com.ticxo.modelengine.v26_3.entity.EntityContainer; +import com.ticxo.modelengine.v26_3.entity.EntityUtils; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class LeashParser implements BehaviorRendererParser { + public void sendToClients(LeashRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + HashSet stop = new HashSet<>(data.getStopTracking()); + stop.removeAll(data.getTracking().keySet()); + this.remove(stop, renderer); + } + + public void destroy(LeashRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (LeashRenderer.Leash leash : renderer.getRendered().values()) { + set.add((Packet)this.link(leash, false)); + set.add(this.move(leash)); + } + + for (LeashRenderer.Leash leash : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(leash)); + set.add((Packet)this.pivotData(leash)); + set.add((Packet)this.leashSpawn(leash)); + set.add((Packet)this.leashData(leash)); + set.add((Packet)this.mount(leash)); + set.add((Packet)this.link(leash, true)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + set.add( + (Packet)(new ClientboundRemoveEntitiesPacket( + IntArrayList.toList(destroy.values().stream().mapMultiToInt((leashx, intConsumer) -> { + intConsumer.accept(leashx.getLeashId()); + intConsumer.accept(leashx.getPivotId()); + })) + )) + ); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, LeashRenderer renderer) { + if (!targets.isEmpty()) { + Map leashes = renderer.getRendered(); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(IntArrayList.toList(leashes.values().stream().mapMultiToInt((leash, intConsumer) -> { + intConsumer.accept(leash.getLeashId()); + intConsumer.accept(leash.getPivotId()); + })))); + } + } + + private Packets.PacketSupplier pivotSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUUID(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + + private ClientboundAddEntityPacket leashSpawn(LeashRenderer.Leash renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getLeashId(), renderer.getLeastUUID(), pos.x, pos.y - 0.45, pos.z - 0.2, 0.0F, 0.0F, EntityTypes.BAT, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket pivotData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetEntityDataPacket leashData(LeashRenderer.Leash renderer) { + return new ClientboundSetEntityDataPacket(renderer.getLeashId(), EntityUtils.DEFAULT_BAT_DATA); + } + + private ClientboundSetPassengersPacket mount(LeashRenderer.Leash renderer) { + ArrayList passengers = new ArrayList<>(1); + passengers.add(renderer.getLeashId()); + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), passengers)); + } + + private Object move(LeashRenderer.Leash renderer) { + if (!renderer.getPosition().isDirty()) { + return null; + } else { + Vector3f pos = renderer.getPosition().get(); + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), pos.add(0.0F, -0.45F, -0.2F, new Vector3f())); + } + } + + private ClientboundSetEntityLinkPacket link(LeashRenderer.Leash renderer, boolean spawn) { + if (!spawn && !renderer.getConnected().isDirty()) { + return null; + } else { + renderer.getConnected().clearDirty(); + return new ClientboundSetEntityLinkPacket(EntityContainer.of(renderer.getLeashId()), EntityContainer.of(renderer.getConnected().get())); + } + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/MountParser.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/MountParser.java new file mode 100644 index 0000000..7fcc47a --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/MountParser.java @@ -0,0 +1,197 @@ +package com.ticxo.modelengine.v26_3.parser.behavior; + +import com.google.common.collect.Lists; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.MountRenderer; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_3.entity.EntityContainer; +import com.ticxo.modelengine.v26_3.entity.EntityUtils; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket.Rot; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class MountParser implements BehaviorRendererParser { + public void sendToClients(MountRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(MountRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + set.add((Packet)this.mountHealth(mount)); + set.add((Packet)this.mountMaxHealth(mount)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (MountRenderer.Mount mount : renderer.getRendered().values()) { + if (mount.getPosition().isDirty()) { + set.add(this.pivotMove(mount)); + mount.getPosition().clearDirty(); + } + + if (mount.getYaw().isDirty()) { + set.add((Packet)this.mountRotate(mount)); + mount.getYaw().clearDirty(); + } + + if (mount.getHealth().isDirty()) { + set.add((Packet)this.mountHealth(mount)); + mount.getHealth().clearDirty(); + } + + if (mount.getMaxHealth().isDirty()) { + set.add((Packet)this.mountMaxHealth(mount)); + mount.getMaxHealth().clearDirty(); + } + + if (mount.getPassengers().isDirty()) { + set.add((Packet)this.mount(mount)); + mount.getPassengers().clearDirty(); + } + } + + for (MountRenderer.Mount mount : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(mount)); + set.add((Packet)this.pivotData(mount)); + set.add((Packet)this.mountSpawn(mount)); + set.add((Packet)this.mountData(mount)); + set.add((Packet)this.pivotMount(mount)); + set.add((Packet)this.mount(mount)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(MountRenderer.Mount::getMountId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, MountRenderer renderer) { + if (!targets.isEmpty()) { + Collection mounts = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(mounts.size() * 2); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getPivotId))); + entityIds.addAll(IntArrayList.toList(mounts.stream().mapToInt(MountRenderer.Mount::getMountId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_PIVOT_DISPLAY_DATA); + } + + private ClientboundAddEntityPacket mountSpawn(MountRenderer.Mount renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getMountId(), + renderer.getMountUuid(), + pos.x, + pos.y, + pos.z, + 0.0F, + TMath.byteToRot(renderer.getYaw().get()), + EntityTypes.ARMOR_STAND, + 0, + Vec3.ZERO, + 0.0 + ); + } + + private ClientboundSetEntityDataPacket mountData(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), EntityUtils.DEFAULT_ARMOR_STAND_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getMountId())); + } + + private ClientboundSetPassengersPacket mount(MountRenderer.Mount renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getMountId(), renderer.getPassengers())); + } + + private Packets.PacketSupplier pivotMove(MountRenderer.Mount renderer) { + return NetworkUtils.createDisplayPivotTeleport(renderer.getPivotId(), renderer.getPosition().get()); + } + + private Rot mountRotate(MountRenderer.Mount renderer) { + return new Rot(renderer.getMountId(), renderer.getYaw().get(), (byte)0, false); + } + + private ClientboundSetEntityDataPacket mountHealth(MountRenderer.Mount renderer) { + return new ClientboundSetEntityDataPacket(renderer.getMountId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, renderer.getHealth().get()))); + } + + private ClientboundUpdateAttributesPacket mountMaxHealth(MountRenderer.Mount renderer) { + AttributeInstance attributeInstance = new AttributeInstance(Attributes.MAX_HEALTH, onDirty -> {}); + attributeInstance.setBaseValue(renderer.getMaxHealth().get().floatValue()); + return new ClientboundUpdateAttributesPacket(renderer.getMountId(), Lists.newArrayList(new AttributeInstance[]{attributeInstance})); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/NameTagParser.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/NameTagParser.java new file mode 100644 index 0000000..c25fa0a --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/NameTagParser.java @@ -0,0 +1,184 @@ +package com.ticxo.modelengine.v26_3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.NameTagRenderer; +import com.ticxo.modelengine.v26_3.entity.EntityContainer; +import com.ticxo.modelengine.v26_3.entity.EntityUtils; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.joml.Vector3f; + +public class NameTagParser implements BehaviorRendererParser { + private float viewRange = 4096.0F; + + public void sendToClients(NameTagRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(NameTagRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + for (NameTagRenderer.NameTag nameTag : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTag)); + set.add((Packet)this.pivotData(nameTag, true)); + set.add((Packet)this.tagSpawn(nameTag)); + set.add((Packet)this.tagData(nameTag, true)); + set.add((Packet)this.pivotMount(nameTag)); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (NameTagRenderer.NameTag nameTag : renderer.getRendered().values()) { + set.add((Packet)this.tagData(nameTag, false)); + if (nameTag.getPosition().isDirty()) { + set.add(this.pivotMove(nameTag)); + nameTag.getPosition().clearDirty(); + } + } + + for (NameTagRenderer.NameTag nameTagx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(nameTagx)); + set.add((Packet)this.pivotData(nameTagx, true)); + set.add((Packet)this.tagSpawn(nameTagx)); + set.add((Packet)this.tagData(nameTagx, true)); + set.add((Packet)this.pivotMount(nameTagx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, NameTagRenderer renderer) { + if (!targets.isEmpty()) { + Collection nameTags = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(nameTags.size() * 2); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getPivotId))); + entityIds.addAll(IntArrayList.toList(nameTags.stream().mapToInt(NameTagRenderer.NameTag::getTagId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + return !spawn ? null : new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + } + + private ClientboundAddEntityPacket tagSpawn(NameTagRenderer.NameTag renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getTagId(), renderer.getTagUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.TEXT_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket tagData(NameTagRenderer.NameTag renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(7); + renderer.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + renderer.getTranslate().ifDirty(flag -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getScale().ifDirty(flag -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, flag)), spawn); + renderer.getTextOpacity().ifDirty(flag -> entityData.add(new DataValue(26, EntityDataSerializers.BYTE, flag)), spawn); + renderer.getBackgroundColor().ifDirty(flag -> entityData.add(new DataValue(25, EntityDataSerializers.INT, flag)), spawn); + renderer.getLineWidth().ifDirty(flag -> entityData.add(new DataValue(24, EntityDataSerializers.INT, flag)), spawn); + renderer.getStyle().ifDirty(flags -> entityData.add(new DataValue(27, EntityDataSerializers.BYTE, flags)), spawn); + renderer.getBillboard().ifDirty(flag -> { + byte value = switch (flag) { + case FIXED -> 0; + case VERTICAL -> 1; + case HORIZONTAL -> 2; + case CENTER -> 3; + default -> throw new MatchException(null, null); + }; + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, value)); + }, spawn); + renderer.getJsonString() + .ifDirty( + jsonString -> { + if (jsonString == null) { + entityData.add(new DataValue(23, EntityDataSerializers.COMPONENT, Component.empty())); + } else { + entityData.add( + new DataValue(23, EntityDataSerializers.COMPONENT, Optional.ofNullable(CraftChatMessage.fromJSON(jsonString)).orElse(Component.empty())) + ); + } + }, + spawn + ); + renderer.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getTagId(), entityData); + } + } + + private Object pivotMove(NameTagRenderer.NameTag renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(NameTagRenderer.NameTag renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getTagId())); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/SegmentParser.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/SegmentParser.java new file mode 100644 index 0000000..d5ea8ee --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/SegmentParser.java @@ -0,0 +1,205 @@ +package com.ticxo.modelengine.v26_3.parser.behavior; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SegmentRenderer; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_3.entity.EntityContainer; +import com.ticxo.modelengine.v26_3.entity.EntityUtils; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.joml.Vector3f; + +public class SegmentParser implements BehaviorRendererParser { + private final List cleanupQueue = new ArrayList<>(); + private float viewRange = 4096.0F; + + public void sendToClients(SegmentRenderer renderer) { + this.cleanupQueue.clear(); + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + } + + public void destroy(SegmentRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Packets set, Map map) { + for (SegmentRenderer.Pivot pivot : map.values()) { + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + for (SegmentRenderer.SegmentDisplayBone bone : pivot.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + this.cleanupQueue.add(pivot::clearDirty); + } + } + + private void spawn(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + this.spawn(set, renderer.getRendered()); + this.spawn(set, renderer.getSpawnQueue()); + NetworkUtils.sendBundled(targets, set); + } + } + + private void update(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + IntArrayList destroy = new IntArrayList(); + + for (SegmentRenderer.Pivot pivot : renderer.getRendered().values()) { + set.add(this.pivotTeleport(pivot)); + pivot.getRendered().values().forEach(bone -> { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + set.add(this.displayData(boneData, false)); + } + } + + scheme.getAdded().forEach(boneDatax -> { + set.add((Packet)this.displaySpawn(pivot, boneDatax)); + set.add(this.displayData(boneDatax, true)); + }); + scheme.getRemoved().forEach(boneDatax -> destroy.add(boneDatax.getId())); + }); + this.cleanupQueue.add(pivot::clearDirty); + } + + this.spawn(set, renderer.getSpawnQueue()); + renderer.getDestroyQueue().forEach((s, pivotx) -> { + destroy.add(pivotx.getId()); + destroy.addAll(pivotx.getPassengers()); + }); + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(destroy))); + } + + NetworkUtils.sendBundled(targets, set); + } + } + + private void remove(Set targets, SegmentRenderer renderer) { + if (!targets.isEmpty()) { + Collection pivots = renderer.getRendered().values(); + IntArrayList ids = new IntArrayList(); + pivots.forEach(pivot -> { + ids.add(pivot.getId()); + ids.addAll(pivot.getPassengers()); + }); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(ids)); + } + } + + private Packets.PacketSupplier pivotSpawn(SegmentRenderer.Pivot pivot) { + return NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SegmentRenderer.Pivot pivot) { + return new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundSetPassengersPacket pivotMount(SegmentRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(SegmentRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + this.cleanupQueue.add(() -> pivot.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundAddEntityPacket displaySpawn(SegmentRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + if (!force && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + return uuid -> this.displayData(uuid, boneData, force); + } + } + + private ClientboundSetEntityDataPacket displayData(UUID uuid, DisplayBone.BoneData boneData, boolean force) { + DisplayBone bone = boneData.getBone(); + ArrayList> entityData = new ArrayList<>(13); + if (force) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } else if (bone.isTransformDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + byte update = bone.getSnapshotHandler().getUpdate(uuid); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : 1)), force); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color)), force); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/SubHitboxParser.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/SubHitboxParser.java new file mode 100644 index 0000000..2dd57a5 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/behavior/SubHitboxParser.java @@ -0,0 +1,148 @@ +package com.ticxo.modelengine.v26_3.parser.behavior; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.model.bone.render.BehaviorRendererParser; +import com.ticxo.modelengine.api.model.bone.render.renderer.SubHitboxRenderer; +import com.ticxo.modelengine.v26_3.entity.EntityContainer; +import com.ticxo.modelengine.v26_3.entity.EntityUtils; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +public class SubHitboxParser implements BehaviorRendererParser { + public void sendToClients(SubHitboxRenderer renderer) { + IEntityData data = renderer.getModelRenderer().getActiveModel().getModeledEntity().getBase().getData(); + this.update(data.getTracking().keySet(), renderer); + this.spawn(data.getStartTracking(), renderer); + this.remove(data.getStopTracking(), renderer); + } + + public void destroy(SubHitboxRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitbox)); + set.add((Packet)this.pivotData(subHitbox)); + set.add((Packet)this.hitboxSpawn(subHitbox)); + set.add((Packet)this.hitboxData(subHitbox, true)); + set.add((Packet)this.pivotMount(subHitbox)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void update(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + + for (SubHitboxRenderer.SubHitbox subHitbox : renderer.getRendered().values()) { + set.add((Packet)this.hitboxData(subHitbox, false)); + if (subHitbox.getPosition().isDirty()) { + set.add(this.pivotMove(subHitbox)); + subHitbox.getPosition().clearDirty(); + } + } + + for (SubHitboxRenderer.SubHitbox subHitboxx : renderer.getSpawnQueue().values()) { + set.add(this.pivotSpawn(subHitboxx)); + set.add((Packet)this.pivotData(subHitboxx)); + set.add((Packet)this.hitboxSpawn(subHitboxx)); + set.add((Packet)this.hitboxData(subHitboxx, true)); + set.add((Packet)this.pivotMount(subHitboxx)); + } + + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + IntArrayList entityIds = new IntArrayList(destroy.size() * 2); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(destroy.values().stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + set.add((Packet)(new ClientboundRemoveEntitiesPacket(entityIds))); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + NetworkUtils.sendBundled(targets, set, player -> player != base.getOriginal()); + } + } + + private void remove(Set targets, SubHitboxRenderer renderer) { + if (!targets.isEmpty()) { + Collection subHitboxes = renderer.getRendered().values(); + IntArrayList entityIds = new IntArrayList(subHitboxes.size() * 2); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getPivotId))); + entityIds.addAll(IntArrayList.toList(subHitboxes.stream().mapToInt(SubHitboxRenderer.SubHitbox::getHitboxId))); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotSpawn(renderer.getPivotId(), renderer.getPivotUuid(), renderer.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetEntityDataPacket(renderer.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private Object pivotMove(SubHitboxRenderer.SubHitbox renderer) { + return NetworkUtils.createPivotMove(renderer.getPivotId(), renderer.getPositionCodec(), renderer.getPosition().get()); + } + + private ClientboundSetPassengersPacket pivotMount(SubHitboxRenderer.SubHitbox renderer) { + return new ClientboundSetPassengersPacket(EntityContainer.of(renderer.getPivotId(), renderer.getHitboxId())); + } + + private ClientboundAddEntityPacket hitboxSpawn(SubHitboxRenderer.SubHitbox renderer) { + Vector3f pos = renderer.getPosition().get(); + return new ClientboundAddEntityPacket( + renderer.getHitboxId(), renderer.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket hitboxData(SubHitboxRenderer.SubHitbox renderer, boolean spawn) { + if (!spawn && !renderer.isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(4); + renderer.getWidth().ifDirty(width -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, width)), spawn); + renderer.getHeight().ifDirty(height -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, height)), spawn); + renderer.clearDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(renderer.getHitboxId(), entityData); + } + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/model/DisplayParser.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/model/DisplayParser.java new file mode 100644 index 0000000..a8dda23 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/model/DisplayParser.java @@ -0,0 +1,791 @@ +package com.ticxo.modelengine.v26_3.parser.model; + +import com.ticxo.modelengine.api.entity.BaseEntity; +import com.ticxo.modelengine.api.entity.BukkitEntity; +import com.ticxo.modelengine.api.entity.CullType; +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.lod.AnimationLODHandler; +import com.ticxo.modelengine.api.model.ModeledEntity; +import com.ticxo.modelengine.api.model.render.DisplayBone; +import com.ticxo.modelengine.api.model.render.DisplayFire; +import com.ticxo.modelengine.api.model.render.DisplayRenderer; +import com.ticxo.modelengine.api.model.render.ModelRendererParser; +import com.ticxo.modelengine.api.nms.network.ModPlayerTracker; +import com.ticxo.modelengine.api.utils.data.PooledCollection; +import com.ticxo.modelengine.api.utils.data.UpdateScheme; +import com.ticxo.modelengine.api.utils.math.TMath; +import com.ticxo.modelengine.v26_3.entity.EntityContainer; +import com.ticxo.modelengine.v26_3.entity.EntityUtils; +import com.ticxo.modelengine.v26_3.network.utils.BulkEntityDataEncoder; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_3.network.utils.Packets; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.util.Brightness; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.Display.BillboardConstraints; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.Nullable; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class DisplayParser implements ModelRendererParser { + private static final Quaternionf IDENTITY_ROTATION = new Quaternionf(); + private final Set noCullPlayers = new HashSet<>(); + private final Set noCullForcePlayers = new HashSet<>(); + private final Set movementOnlyPlayers = new HashSet<>(); + private final Set culledPlayers = new HashSet<>(); + private final List cleanupQueue = new ArrayList<>(); + private ModeledEntity modeledEntity; + private float viewRange = 4096.0F; + private Object pivotMove; + private Object hitboxMove; + private static StreamCodec CUSTOM_PAYLOAD_CODEC; + + public void sendToClients(DisplayRenderer renderer) { + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + this.cleanupQueue.clear(); + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + this.modeledEntity = renderer.getActiveModel().getModeledEntity(); + this.viewRange = renderer.getActiveModel().getViewRange(); + this.pivotMove = this.pivotTeleport(renderer.getPivot()); + this.hitboxMove = this.hitboxTeleport(renderer.getHitbox()); + + for (Entry entry : data.getTracking().entrySet()) { + switch ((CullType)entry.getValue()) { + case NO_CULL: + if (renderer.pollFullUpdate(entry.getKey())) { + this.noCullForcePlayers.add(entry.getKey()); + } else { + this.noCullPlayers.add(entry.getKey()); + } + break; + case MOVEMENT_ONLY: + renderer.pushFullUpdate(entry.getKey()); + this.movementOnlyPlayers.add(entry.getKey()); + break; + case CULLED: + this.culledPlayers.add(entry.getKey()); + } + } + + if (renderer.pollFirstSpawn()) { + HashSet set = new HashSet<>((int)((this.movementOnlyPlayers.size() + this.noCullPlayers.size() + this.noCullForcePlayers.size()) / 0.75F) + 1); + set.addAll(this.movementOnlyPlayers); + set.addAll(this.noCullPlayers); + set.addAll(this.noCullForcePlayers); + this.spawn(set, renderer); + } else { + Set spawning = data.getStartTracking(); + this.spawn(spawning, renderer); + this.updateRealtime(excluding(this.movementOnlyPlayers, spawning), renderer, true, false); + this.updateRealtime(excluding(this.noCullPlayers, spawning), renderer, false, false); + this.updateRealtime(excluding(this.noCullForcePlayers, spawning), renderer, false, true); + this.updateCulled(this.culledPlayers, renderer); + this.remove(data.getStopTracking(), renderer); + } + + if (renderer.hasGlowAudience()) { + this.updateAudienceGlow(renderer, data.getTracking().keySet(), data.getStartTracking(), this.noCullForcePlayers); + } + + this.noCullPlayers.clear(); + this.noCullForcePlayers.clear(); + this.movementOnlyPlayers.clear(); + this.culledPlayers.clear(); + renderer.getPivot().clearDirty(); + renderer.getHitbox().clearDirty(); + PooledCollection fireDisplay = renderer.getHitbox().getFireDisplay(); + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + this.cleanupQueue.forEach(Runnable::run); + this.cleanupQueue.clear(); + this.pivotMove = null; + this.hitboxMove = null; + } + + private static Set excluding(Set targets, Set excluded) { + if (!targets.isEmpty() && !excluded.isEmpty()) { + HashSet filtered = new HashSet<>(targets); + filtered.removeAll(excluded); + return filtered; + } else { + return targets; + } + } + + private void updateAudienceGlow(DisplayRenderer renderer, Set current, Set startTracking, Set forceUpdates) { + for (DisplayBone bone : renderer.getRendered().values()) { + Set audience = bone.getGlowAudience().get(); + if (audience != null) { + boolean changed = bone.isAudienceGlowDirty(); + if (changed || !startTracking.isEmpty() || !forceUpdates.isEmpty()) { + boolean glowing = bone.getAudienceGlowing().get(); + int color = bone.getAudienceGlowColor().get(); + Set on = new HashSet<>(); + Set off = new HashSet<>(); + if (changed) { + for (UUID uuid : current) { + if (glowing && audience.contains(uuid)) { + on.add(uuid); + } else { + off.add(uuid); + } + } + + bone.clearAudienceGlowDirty(); + } else if (glowing) { + for (UUID uuidx : startTracking) { + if (audience.contains(uuidx)) { + on.add(uuidx); + } + } + + for (UUID uuidxx : forceUpdates) { + if (audience.contains(uuidxx)) { + on.add(uuidxx); + } + } + } + + if (!on.isEmpty() || !off.isEmpty()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + int id = boneData.getId(); + if (!on.isEmpty()) { + NetworkUtils.send(on, this.audienceGlowData(id, true, color)); + } + + if (!off.isEmpty()) { + NetworkUtils.send(off, this.audienceGlowData(id, false, color)); + } + } + } + } + } + } + } + + private ClientboundSetEntityDataPacket audienceGlowData(int entityId, boolean glowing, int color) { + ArrayList> entityData = new ArrayList<>(2); + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(glowing ? 96 : 32))); + if (glowing) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + + return new ClientboundSetEntityDataPacket(entityId, entityData); + } + + public void destroy(DisplayRenderer renderer) { + IEntityData data = renderer.getActiveModel().getModeledEntity().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer); + } + + private void spawn(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotSpawn(pivot)); + set.add((Packet)this.pivotData(pivot)); + + for (DisplayBone bone : renderer.getRendered().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + set.add((Packet)this.pivotMount(pivot)); + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + if (base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player owner && targets.contains(owner.getUniqueId())) { + NetworkUtils.sendBundled(owner.getUniqueId(), set); + } + + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + set.add(this.hitboxSpawnPivot(hitbox)); + set.add((Packet)this.hitboxDataPivot(hitbox)); + set.add((Packet)this.hitboxSpawn(hitbox)); + set.add((Packet)this.hitboxData(hitbox, true)); + set.add((Packet)this.shadowSpawn(hitbox)); + set.add((Packet)this.shadowData(hitbox, true)); + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> { + set.add((Packet)this.fireSpawn(hitbox, displayFire)); + set.add((Packet)this.fireData(displayFire, true)); + }); + } + + set.add((Packet)this.hitboxMount(hitbox)); + NetworkUtils.sendBundled(targets, set, player -> !player.getUniqueId().equals(base.getUUID())); + } + } + + private void updateRealtime(Set targets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!targets.isEmpty()) { + Set modTargets = null; + Set vanillaTargets = targets; + + for (UUID uuid : targets) { + if (ModPlayerTracker.hasClientMod(uuid)) { + if (modTargets == null) { + modTargets = new HashSet<>(); + vanillaTargets = new HashSet<>(targets); + } + + modTargets.add(uuid); + vanillaTargets.remove(uuid); + } + } + + Packets set = new Packets(); + Packets boneSet = modTargets != null ? new Packets() : set; + HashSet destroy = new HashSet<>(); + DisplayRenderer.Pivot pivot = renderer.getPivot(); + set.add(this.pivotMove); + set.add((Packet)this.pivotCameraResize(pivot)); + if (!movementOnly) { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add(this.displayData(boneData, false, transformOnly)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } else { + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + boneSet.add((Packet)this.displayVisibleData(boneData)); + } + } + + if (scheme.hasUpdate()) { + scheme.getAdded().forEach(boneData -> { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + }); + scheme.getRemoved().forEach(boneData -> destroy.add(boneData.getId())); + } + } + } + + for (DisplayBone bone : renderer.getSpawnQueue().values()) { + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + set.add((Packet)this.displaySpawn(pivot, boneData)); + set.add(this.displayData(boneData, true, false)); + } + } + + renderer.getDestroyQueue().forEach((s, bones) -> bones.getModel().forEach((uuidx, boneData) -> destroy.add(boneData.getId()))); + if (pivot.getPassengers().isDirty()) { + set.add((Packet)this.pivotMount(pivot)); + } + + BaseEntity base = renderer.getActiveModel().getModeledEntity().getBase(); + UUID owner = base instanceof BukkitEntity bukkitEntity && bukkitEntity.getOriginal() instanceof Player && targets.contains(base.getUUID()) + ? base.getUUID() + : null; + Packets hitboxSet = owner == null ? set : new Packets(); + HashSet hitboxDestroy = owner == null ? destroy : new HashSet<>(); + DisplayRenderer.Hitbox hitbox = renderer.getHitbox(); + AtomicBoolean updateHitboxMount = new AtomicBoolean(false); + hitboxSet.add(this.hitboxMove); + if (hitbox.getHitboxVisible().isDirty()) { + if (hitbox.isHitboxVisible()) { + hitboxSet.add((Packet)this.hitboxSpawn(hitbox)); + hitboxSet.add((Packet)this.hitboxData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getHitboxId()); + } + } else { + hitboxSet.add((Packet)this.hitboxData(hitbox, false)); + } + + if (hitbox.getShadowVisible().isDirty()) { + if (hitbox.isShadowVisible()) { + hitboxSet.add((Packet)this.shadowSpawn(hitbox)); + hitboxSet.add((Packet)this.shadowData(hitbox, true)); + updateHitboxMount.set(true); + } else { + hitboxDestroy.add(hitbox.getShadowId()); + } + } else { + hitboxSet.add((Packet)this.shadowData(hitbox, false)); + } + + PooledCollection fireDisplay = hitbox.getFireDisplay(); + if (hitbox.getFireVisible().isDirty()) { + if (hitbox.isFireVisible()) { + fireDisplay.getInUse().forEach(displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }); + } else { + fireDisplay.getAll().forEach(displayFire -> hitboxDestroy.add(displayFire.getId())); + } + } else { + fireDisplay.processAll( + displayFire -> { + updateHitboxMount.set(true); + hitboxSet.add((Packet)this.fireSpawn(hitbox, displayFire)); + hitboxSet.add((Packet)this.fireData(displayFire, true)); + }, + displayFire -> hitboxSet.add((Packet)this.fireData(displayFire, false)), + displayFire -> hitboxDestroy.add(displayFire.getId()) + ); + } + + if (!fireDisplay.getCreated().isEmpty()) { + fireDisplay.getCreated().clear(); + } + + if (!fireDisplay.getReleased().isEmpty()) { + fireDisplay.getReleased().clear(); + } + + if (updateHitboxMount.get()) { + hitboxSet.add((Packet)this.hitboxMount(hitbox)); + } + + if (!destroy.isEmpty()) { + set.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(destroy)))); + } + + if (hitboxDestroy != destroy && !hitboxDestroy.isEmpty()) { + hitboxSet.add((Packet)(new ClientboundRemoveEntitiesPacket(new IntArrayList(hitboxDestroy)))); + } + + if (modTargets != null) { + NetworkUtils.sendBundled(targets, set); + NetworkUtils.sendBundled(vanillaTargets, boneSet); + this.sendBulkBoneData(modTargets, renderer, movementOnly, transformOnly); + } else { + NetworkUtils.sendBundled(targets, set); + } + + if (hitboxSet != set) { + NetworkUtils.sendBundled(targets, hitboxSet, player -> !player.getUniqueId().equals(owner)); + } + } + } + + private void sendBulkBoneData(Set modTargets, DisplayRenderer renderer, boolean movementOnly, boolean transformOnly) { + if (!movementOnly) { + for (UUID uuid : modTargets) { + BulkEntityDataEncoder encoder = new BulkEntityDataEncoder(); + Packets fallbackPackets = new Packets(); + + for (DisplayBone bone : renderer.getRendered().values()) { + UpdateScheme scheme = bone.getModelUpdateScheme(); + + for (DisplayBone.BoneData boneData : bone.getModel().values()) { + switch (scheme.getUpdateMode(boneData)) { + case NONE: + case UPDATE: + if (boneData.getModel().isDirty()) { + fallbackPackets.add((Packets.PacketSupplier)(u -> this.displayData(u, null, boneData, false, transformOnly))); + } else if (!boneData.getBone().isSkippable()) { + this.encodeBoneData(encoder, uuid, null, boneData, false, transformOnly); + } else { + AnimationLODHandler.LODTracker tracker = this.modeledEntity.getAnimationLodHandler().tick(uuid); + if (!tracker.isCanSkip()) { + this.encodeBoneData(encoder, uuid, tracker, boneData, false, transformOnly); + } + } + } + } + } + + if (encoder.getEntryCount() > 0) { + byte[] data = encoder.build(); + RegistryFriendlyByteBuf buf = NetworkUtils.createByteBuf(); + buf.writeUtf("modelengine:bulk_data"); + buf.writeBytes(data); + Packet packet = createCustomPayload(buf); + if (packet != null) { + NetworkUtils.send(uuid, packet); + } + } + + NetworkUtils.sendBundled(uuid, fallbackPackets); + } + } + } + + private static Packet createCustomPayload(RegistryFriendlyByteBuf buf) { + try { + if (CUSTOM_PAYLOAD_CODEC == null) { + Field field = ClientboundCustomPayloadPacket.class.getField("GAMEPLAY_STREAM_CODEC"); + field.setAccessible(true); + CUSTOM_PAYLOAD_CODEC = (StreamCodec)field.get(null); + } + + return (Packet)CUSTOM_PAYLOAD_CODEC.decode(buf); + } catch (Exception var2) { + var2.printStackTrace(); + return null; + } + } + + private void encodeBoneData( + BulkEntityDataEncoder encoder, + UUID uuid, + @Nullable AnimationLODHandler.LODTracker tracker, + DisplayBone.BoneData boneData, + boolean force, + boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + if (force || transformOnly || bone.isDirty() || boneData.getModel().isDirty()) { + byte update = bone.getSnapshotHandler().getUpdate(uuid); + boolean wouldWriteTransform = force || update != 0; + boolean wouldWriteRender = force || bone.isRenderDirty(); + if (wouldWriteTransform || wouldWriteRender) { + BulkEntityDataEncoder.EntryWriter entry = encoder.startEntry(boneData.getId()); + bone.getPosition().ifDirty(v -> entry.translation(new Vector3f(v)), force || TMath.getBit(update, 0)); + bone.getLeftRotation().ifDirty(q -> entry.leftRotation(new Quaternionf(q)), force || TMath.getBit(update, 1)); + bone.getScale().ifDirty(v -> entry.scale(new Vector3f(v)), force || TMath.getBit(update, 2)); + bone.getRightRotation().ifDirty(q -> entry.rightRotation(new Quaternionf(q)), force || TMath.getBit(update, 3)); + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entry.transformDuration(flag ? 0 : lodTick), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> bone.getGlowColor().ifDirty(color -> entry.glowData((byte)(flag ? 96 : 32), color), true), force); + bone.getBrightness().ifDirty(entry::brightness, force); + boolean hasBillboard = bone.getBillboard().isDirty() || force; + boolean hasVisibility = bone.getVisibility().isDirty() || force; + boolean hasDisplayType = bone.getDisplay().isDirty() || force; + if (hasBillboard || hasVisibility || hasDisplayType) { + entry.renderData( + (byte)bone.getBillboard().get().ordinal(), + bone.getVisibility().get() ? this.viewRange : 0.0F, + bone.getDisplay().get() == null ? 0 : (byte)bone.getDisplay().get().ordinal() + ); + } + + entry.finish(); + } + } + } + + private void updateCulled(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + Map destroy = renderer.getDestroyQueue(); + if (!destroy.isEmpty()) { + destroy.values() + .stream() + .mapMultiToInt((bones, intConsumer) -> bones.getModel().forEach((uuid, boneData) -> intConsumer.accept(boneData.getId()))) + .forEach(entityIds::add); + } + + if (!entityIds.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + } + + private void remove(Set targets, DisplayRenderer renderer) { + if (!targets.isEmpty()) { + IntArrayList entityIds = new IntArrayList(); + + for (DisplayBone bone : new ArrayList<>(renderer.getRendered().values())) { + targets.forEach(uuid -> bone.getSnapshotHandler().remove(uuid)); + bone.getModel().forEach((integer, boneData) -> entityIds.add(boneData.getId())); + } + + entityIds.add(renderer.getPivot().getId()); + entityIds.add(renderer.getHitbox().getPivotId()); + entityIds.add(renderer.getHitbox().getHitboxId()); + entityIds.add(renderer.getHitbox().getShadowId()); + renderer.getHitbox().getFireDisplay().getAll().forEach(displayFire -> entityIds.add(displayFire.getId())); + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(entityIds)); + } + } + + private Packets.PacketSupplier pivotSpawn(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotSpawn(pivot.getId(), pivot.getUuid(), pivot.getPosition().get()); + } + + private ClientboundSetEntityDataPacket pivotData(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() + ? new ClientboundSetEntityDataPacket(pivot.getId(), this.cameraPivotData(pivot.getCameraHeight().get())) + : new ClientboundSetEntityDataPacket(pivot.getId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private List> cameraPivotData(float height) { + return List.of( + new DataValue(0, EntityDataSerializers.BYTE, (byte)32), + new DataValue(8, EntityDataSerializers.FLOAT, 0.0F), + new DataValue(9, EntityDataSerializers.FLOAT, height) + ); + } + + private ClientboundSetPassengersPacket pivotMount(DisplayRenderer.Pivot pivot) { + return new ClientboundSetPassengersPacket(EntityContainer.of(pivot.getId(), pivot.getPassengers())); + } + + private Object pivotTeleport(DisplayRenderer.Pivot pivot) { + if (!pivot.getPosition().isDirty()) { + return null; + } else { + return pivot.isCameraPivot() + ? NetworkUtils.createCameraPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get(), pivot.getCameraHeight().get()) + : NetworkUtils.createPivotMove(pivot.getId(), pivot.getPositionCodec(), pivot.getPosition().get()); + } + } + + private ClientboundSetEntityDataPacket pivotCameraResize(DisplayRenderer.Pivot pivot) { + return pivot.isCameraPivot() && pivot.getCameraHeight().isDirty() + ? new ClientboundSetEntityDataPacket(pivot.getId(), List.of(new DataValue(9, EntityDataSerializers.FLOAT, pivot.getCameraHeight().get()))) + : null; + } + + private ClientboundAddEntityPacket displaySpawn(DisplayRenderer.Pivot pivot, DisplayBone.BoneData boneData) { + Vector3f pos = pivot.getPosition().get(); + return new ClientboundAddEntityPacket(boneData.getId(), boneData.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private Packets.PacketSupplier displayData(DisplayBone.BoneData boneData, boolean force, boolean transformOnly) { + DisplayBone bone = boneData.getBone(); + if (!force && !transformOnly && !bone.isDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + this.cleanupQueue.add(bone::clearDirty); + this.cleanupQueue.add(() -> boneData.getModel().clearDirty()); + if (force) { + return uuid -> this.displayData(uuid, this.modeledEntity.getAnimationLodHandler().tick(uuid), boneData, true, transformOnly); + } else { + return !bone.isSkippable() + ? uuid -> this.displayData(uuid, null, boneData, false, transformOnly) + : NetworkUtils.lodWrapper(this.modeledEntity, (uuid, tracker) -> this.displayData(uuid, tracker, boneData, false, transformOnly)); + } + } + } + + private ClientboundSetEntityDataPacket displayData( + UUID uuid, @Nullable AnimationLODHandler.LODTracker tracker, DisplayBone.BoneData boneData, boolean force, boolean transformOnly + ) { + DisplayBone bone = boneData.getBone(); + byte update = bone.getSnapshotHandler().getUpdate(uuid); + ArrayList> entityData = new ArrayList<>(13); + if (!force && update != 0) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + int lodTick = tracker == null ? 1 : tracker.getTickDuration().get(); + boolean lodDirty = tracker != null && tracker.getTickDuration().isDirty(); + bone.getStep().ifDirty(flag -> entityData.add(new DataValue(9, EntityDataSerializers.INT, flag ? 0 : lodTick)), force || transformOnly || lodDirty); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32))), force); + bone.getGlowColor().ifDirty(color -> { + if (!force || color != -1) { + entityData.add(new DataValue(22, EntityDataSerializers.INT, color)); + } + }, force); + bone.getBrightness().ifDirty(val -> { + if (!force || val != -1) { + entityData.add(new DataValue(16, EntityDataSerializers.INT, val)); + } + }, force); + bone.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 0)); + bone.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), force || TMath.getBit(update, 2)); + bone.getLeftRotation() + .ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), force || TMath.getBit(update, 1)); + bone.getRightRotation().ifDirty(quaternionf -> { + if (!force || !TMath.isSimilar(quaternionf, IDENTITY_ROTATION)) { + entityData.add(new DataValue(14, EntityDataSerializers.QUATERNION, quaternionf)); + } + }, force || TMath.getBit(update, 3)); + bone.getBillboard().ifDirty(billboard -> { + if (!force || billboard.ordinal() != 0) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal())); + } + }, force); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), force); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), force); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal())), force); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + + private ClientboundSetEntityDataPacket displayVisibleData(DisplayBone.BoneData boneData) { + DisplayBone bone = boneData.getBone(); + if (!bone.isRenderDirty() && !boneData.getModel().isDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(6); + bone.getGlowing().ifDirty(flag -> entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)(flag ? 96 : 32)))); + bone.getGlowColor().ifDirty(color -> entityData.add(new DataValue(22, EntityDataSerializers.INT, color))); + bone.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val))); + bone.getBillboard().ifDirty(billboard -> entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)billboard.ordinal()))); + bone.getVisibility().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F))); + boneData.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack)))); + bone.getDisplay().ifDirty(display -> entityData.add(new DataValue(24, EntityDataSerializers.BYTE, display == null ? 0 : (byte)display.ordinal()))); + this.cleanupQueue.add(bone::clearDirty); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(boneData.getId(), entityData); + } + } + + private Packets.PacketSupplier hitboxSpawnPivot(DisplayRenderer.Hitbox hitbox) { + return hitbox.isPivotVisible() ? NetworkUtils.createPivotSpawn(hitbox.getPivotId(), hitbox.getPivotUuid(), hitbox.getPosition().get()) : null; + } + + private ClientboundSetEntityDataPacket hitboxDataPivot(DisplayRenderer.Hitbox hitbox) { + return !hitbox.isPivotVisible() ? null : new ClientboundSetEntityDataPacket(hitbox.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket hitboxSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isHitboxVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getHitboxId(), hitbox.getHitboxUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.INTERACTION, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket hitboxData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isHitboxVisible() && (hitbox.isHitboxDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(4); + hitbox.getWidth().ifDirty(val -> entityData.add(new DataValue(8, EntityDataSerializers.FLOAT, val)), spawn); + hitbox.getHeight().ifDirty(val -> entityData.add(new DataValue(9, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getHitboxId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket shadowSpawn(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isShadowVisible()) { + return null; + } else { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket( + hitbox.getShadowId(), hitbox.getShadowUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + } + + private ClientboundSetEntityDataPacket shadowData(DisplayRenderer.Hitbox hitbox, boolean spawn) { + if (hitbox.isShadowVisible() && (hitbox.getShadowRadius().isDirty() || spawn)) { + ArrayList> entityData = new ArrayList<>(2); + hitbox.getShadowRadius().ifDirty(val -> entityData.add(new DataValue(18, EntityDataSerializers.FLOAT, val)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(hitbox.getShadowId(), entityData); + } else { + return null; + } + } + + private ClientboundAddEntityPacket fireSpawn(DisplayRenderer.Hitbox hitbox, DisplayFire fire) { + Vector3f pos = hitbox.getPosition().get(); + return new ClientboundAddEntityPacket(fire.getId(), fire.getUuid(), pos.x, pos.y, pos.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0); + } + + private ClientboundSetEntityDataPacket fireData(DisplayFire fire, boolean spawn) { + if (!fire.isDirty() && !spawn) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(2); + if (spawn) { + entityData.add(new DataValue(15, EntityDataSerializers.BYTE, (byte)BillboardConstraints.VERTICAL.ordinal())); + entityData.add(new DataValue(16, EntityDataSerializers.INT, Brightness.FULL_BRIGHT.pack())); + } + + fire.getFireModel().ifDirty(stack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(stack))), spawn); + fire.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + fire.getVisible().ifDirty(flag -> entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, flag ? this.viewRange : 0.0F)), spawn); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(fire.getId(), entityData); + } + } + + private Object hitboxTeleport(DisplayRenderer.Hitbox hitbox) { + if (hitbox.isPivotVisible() && hitbox.getPosition().isDirty()) { + this.cleanupQueue.add(() -> hitbox.getPosition().clearDirty()); + return NetworkUtils.createPivotMove(hitbox.getPivotId(), hitbox.getPositionCodec(), hitbox.getPosition().get()); + } else { + return null; + } + } + + private ClientboundSetPassengersPacket hitboxMount(DisplayRenderer.Hitbox hitbox) { + if (!hitbox.isPivotVisible()) { + return null; + } else { + boolean hitboxVisible = hitbox.isHitboxVisible(); + boolean shadowVisible = hitbox.isShadowVisible(); + ArrayList passengers = new ArrayList<>(2 + hitbox.getFireDisplay().getInUse().size()); + if (hitboxVisible) { + passengers.add(hitbox.getHitboxId()); + } + + if (shadowVisible) { + passengers.add(hitbox.getShadowId()); + } + + if (hitbox.isFireVisible()) { + hitbox.getFireDisplay().getInUse().forEach(displayFire -> passengers.add(displayFire.getId())); + } + + return new ClientboundSetPassengersPacket(EntityContainer.of(hitbox.getPivotId(), passengers)); + } + } +} diff --git a/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/vfx/VFXDisplayParser.java b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/vfx/VFXDisplayParser.java new file mode 100644 index 0000000..714d2e8 --- /dev/null +++ b/nms/v26_3/src/main/java/com/ticxo/modelengine/v26_3/parser/vfx/VFXDisplayParser.java @@ -0,0 +1,124 @@ +package com.ticxo.modelengine.v26_3.parser.vfx; + +import com.ticxo.modelengine.api.entity.data.IEntityData; +import com.ticxo.modelengine.api.vfx.render.VFXDisplayRenderer; +import com.ticxo.modelengine.api.vfx.render.VFXRendererParser; +import com.ticxo.modelengine.v26_3.entity.EntityContainer; +import com.ticxo.modelengine.v26_3.entity.EntityUtils; +import com.ticxo.modelengine.v26_3.network.utils.NetworkUtils; +import com.ticxo.modelengine.v26_3.network.utils.Packets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.syncher.EntityDataSerializers; +import net.minecraft.network.syncher.SynchedEntityData.DataValue; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.phys.Vec3; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ItemDisplay.ItemDisplayTransform; +import org.joml.Vector3f; + +public class VFXDisplayParser implements VFXRendererParser { + public void sendToClients(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + if (renderer.isRespawnRequired()) { + this.teleport(renderer.getVFXModel()); + this.spawn(data.getTracking().keySet(), renderer.getVFXModel()); + renderer.setRespawnRequired(false); + } else { + this.update(data.getTracking().keySet(), renderer.getVFXModel()); + this.spawn(data.getStartTracking(), renderer.getVFXModel()); + this.remove(data.getStopTracking(), renderer.getVFXModel()); + } + } + + public void destroy(VFXDisplayRenderer renderer) { + IEntityData data = renderer.getVFX().getBase().getData(); + HashSet inRange = new HashSet<>(data.getStartTracking()); + inRange.addAll(data.getTracking().keySet()); + inRange.addAll(data.getStopTracking()); + this.remove(inRange, renderer.getVFXModel()); + } + + public void spawn(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.pivotSpawn(vfx)); + set.add((Packet)this.pivotData(vfx)); + set.add((Packet)this.vfxSpawn(vfx)); + set.add((Packet)this.vfxData(vfx, true)); + set.add((Packet)this.mount(vfx)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void update(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + Packets set = new Packets(); + set.add(this.teleport(vfx)); + set.add((Packet)this.vfxData(vfx, false)); + NetworkUtils.sendBundled(targets, set); + } + } + + public void remove(Set targets, VFXDisplayRenderer.VFXModel vfx) { + if (!targets.isEmpty()) { + NetworkUtils.send(targets, new ClientboundRemoveEntitiesPacket(new int[]{vfx.getPivotId(), vfx.getModelId()})); + } + } + + private Packets.PacketSupplier pivotSpawn(VFXDisplayRenderer.VFXModel vfx) { + return NetworkUtils.createPivotSpawn(vfx.getPivotId(), vfx.getPivotUuid(), vfx.getOrigin().get()); + } + + private ClientboundSetEntityDataPacket pivotData(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetEntityDataPacket(vfx.getPivotId(), EntityUtils.DEFAULT_AREA_EFFECT_CLOUD_DATA); + } + + private ClientboundAddEntityPacket vfxSpawn(VFXDisplayRenderer.VFXModel vfx) { + Vector3f location = vfx.getOrigin().get(); + return new ClientboundAddEntityPacket( + vfx.getModelId(), vfx.getModelUuid(), location.x, location.y, location.z, 0.0F, 0.0F, EntityTypes.ITEM_DISPLAY, 0, Vec3.ZERO, 0.0 + ); + } + + private ClientboundSetEntityDataPacket vfxData(VFXDisplayRenderer.VFXModel vfx, boolean spawn) { + if (!spawn && !vfx.isModelDirty()) { + return null; + } else { + ArrayList> entityData = new ArrayList<>(9); + if (spawn) { + entityData.add(new DataValue(0, EntityDataSerializers.BYTE, (byte)32)); + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + entityData.add(new DataValue(9, EntityDataSerializers.INT, 1)); + entityData.add(new DataValue(17, EntityDataSerializers.FLOAT, 4096.0F)); + entityData.add(new DataValue(24, EntityDataSerializers.BYTE, (byte)ItemDisplayTransform.HEAD.ordinal())); + } else if (vfx.isModelDirty()) { + entityData.add(new DataValue(8, EntityDataSerializers.INT, 0)); + } + + vfx.getPosition().ifDirty(vector3f -> entityData.add(new DataValue(11, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getScale().ifDirty(vector3f -> entityData.add(new DataValue(12, EntityDataSerializers.VECTOR3, vector3f)), spawn); + vfx.getLeftRotation().ifDirty(quaternionf -> entityData.add(new DataValue(13, EntityDataSerializers.QUATERNION, quaternionf)), spawn); + vfx.getModel().ifDirty(itemStack -> entityData.add(new DataValue(23, EntityDataSerializers.ITEM_STACK, CraftItemStack.asNMSCopy(itemStack))), spawn); + vfx.getBrightness().ifDirty(val -> entityData.add(new DataValue(16, EntityDataSerializers.INT, val)), spawn); + vfx.clearModelDirty(); + return entityData.isEmpty() ? null : new ClientboundSetEntityDataPacket(vfx.getModelId(), entityData); + } + } + + private Object teleport(VFXDisplayRenderer.VFXModel vfx) { + return !vfx.getOrigin().isDirty() ? null : NetworkUtils.createPivotMove(vfx.getPivotId(), vfx.getPositionCodec(), vfx.getOrigin().get()); + } + + private ClientboundSetPassengersPacket mount(VFXDisplayRenderer.VFXModel vfx) { + return new ClientboundSetPassengersPacket(EntityContainer.of(vfx.getPivotId(), vfx.getModelId())); + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..f220e85 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,24 @@ +pluginManagement { + repositories { + gradlePluginPortal() + maven("https://repo.papermc.io/repository/maven-public/") + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} + +rootProject.name = "ModelEngine" + +include("api", "core", "core21", "core25") + +val nmsModules = listOf( + "v1_19_R3", "v1_20_R1", "v1_20_R2", "v1_20_R3", "v1_20_R4", + "v1_21_R1", "v1_21_R2", "v1_21_R3", "v1_21_R4", "v1_21_R5", "v1_21_R6", "v1_21_R7", + "v26_1", "v26_2", "v26_3", +) +nmsModules.forEach { + include(":nms:$it") + project(":nms:$it").projectDir = file("nms/$it") +}